{% extends "base.html" %} {% block body %}
https://www.acmicpc.net/problem/14041
https://www.acmicpc.net/problem/8295
https://www.acmicpc.net/problem/15151
BJE_15858 Simple Arithmetic (Bronze III)
BJ_1871 좋은 자동차 번호판 (Bronze II)
BJ_1402 아무래도이문제는A번난이도인것같다 (Bronze I)
https://www.acmicpc.net/problem/10867
https://www.acmicpc.net/problem/2578
https://www.acmicpc.net/problem/5635
https://www.acmicpc.net/problem/1063
https://www.acmicpc.net/problem/2998
https://www.acmicpc.net/problem/5800
https://www.acmicpc.net/problem/1145
https://www.acmicpc.net/problem/10158
https://www.acmicpc.net/problem/2670
https://www.acmicpc.net/problem/5347
https://www.acmicpc.net/problem/11332
Students can create id / pw
https://www.youtube.com/watch?v=5Wju2JKyNLY
https://code.visualstudio.com/docs/remote/wsl-tutorial
Get-Content a.txt | python a.py
파이썬 온라인 디버거 (vs 코드 다운 받기 힘든 저학년 위주)
영어 시험 문제집
한글 코딩 문제집
https://chrome.google.com/webstore/detail/solvedac/anenheoccfogllpbpcmbbpcbjpogeehe?hl=ko
온라인 강좌 (가급적 자막 있는 Khan 720p → 없을 시 다른 한국 영상)
Youtube 1~2개 링크 후에 적절한 설명 (난이도 순)
예제 넣고 그에 맞는 GF 문제 만들기 (난이도 순)
설정에서 퀴즈로 만들기, 틀린 문제 정답공개 제거
답은 주관식으로 코드 문제는 (간단하게 코드 적고, 이것의 output은 어떻게 나오냐 식으로)
답 format 은 teaching student 에 기술 후 답 1개만 맞게 (이전 시험 참고)
대단원 (heading 1) | 소단원 (Heading 2)으로 분류 (ctrl + alt + 1 / 2)
소단원에는 • Practice • Test • Code 의 태그가 있음
학생용 링크므로 수정 안됨
황규승 # 질문자
https://www.acmicpc.net/problem/16430 # 문제
a, b = input() # 현재 코드
ValueError: not enough values to unpack (expected 2, got 1) # 에러 내용
a, b = input()
Line 1 in <module> (Solution.py)
www.open.kattis.com 에서 아래에 문제 코드 입력해서 contest 만들기
시험 시작 시 Q&A 에 문제 올리기
일요일에 시험에 정답 teaching_stduent에 올리기
Khan academy 보게 시킨 후 GF / BJ 풀기
3반 친구들은 warm up GF 풀기, BJ로 개념 설명 → Kattis 시험 진행
Easy, Hard 문제 4개씩 BJ에 찾아서 올림
그 다음주는 정답 올리기 (즉 Teaching student에는 8개 시험 정답, 8개 숙제 정답, 8개 숙제가 있음)
백준 코드 안될 때 진행
Easy
홀짝 판별 → if else
몫과 나머지 → Quotient | Remainder
최소값 → min | max | abs
Substring → List | Indexing | Slicing
계산기 → eval
피라미드 → for
단어의 개수 세기 → len
거스름돈 → Quotient | Remainder
Medium
문자열 뒤집기 → reversed
공백 없애기 → for
369 게임 → Quotient | Remainder
소수 판별 → Prime | LCM | GCD
윤년 → if | elif | else
이차 방정식의 해 → Exponent
주사위 놀이 → for
Hard
3과 5의 배수 → Series
n 구하기 → Series
절약 정신 → Prime | LCM | GCD
# # single line comment
""" # multi line comment
written by: Sean Hwang
"""
Print(5) # Error
print(1, 2, 3) # 1 2 3 (default)
print(5, 5, sep='-') # 5-5
print(5) # 5
print(5) # 5
print(5, end=' ') # 5 5
print(5, end=' ')
print(5, " is five") # 5 is five
print(str(5) + " is five") # 5 is five (cast)
print(05)
print(1+'1')
PRINT('123')
print(4.99)
print(--5)
print('1', 1)
print(9999)
print(3 + 5)
print(3.5)
print(ab)
print(5, 5, sep='-')
print(1, end='+'); print(2)
print(2, end='*'); print(3)
print('a', 'z', sep='.')
print('b', 'd', sep='@')
print('a', 1, sep='^')
print(123, end="0"); print(123)
print('ace', end="|"); print('bdf')
print('int', 'float', sep="bool")
print(98,'zxw',sep="::", end="**")
print("문제의 정답")
print(1)
BJ_2557 Hello World (Bronze V)
print("Hello World!")
print("파이팅!!")
print(‘비와이’)
BJ_10718 We love kriii (Bronze V)
print("강한친구 대한육군")
print('강한친구 대한육군')
print(123)
print('Your_ICPC_Team_Name')
print(2020)
print('05')
print(23)
print("2015-01-24")
print("Hello World!")
print(" ' ") # '
print(" ' \" ") # ' "
print("\n") # new line
print("\\") # \
print("\t Hello") # Hello
₩ 와 \ 는 같음
\" # Double Quote
\' # Single Quote
\\ # Backslash
\n # New Line
\r # Carriage Return
\t # Tab
print("*")
print(" ' ")
print(" " ")
print(" \" ")
print(" \'\" ")
print("\")
print("\\")
print("line "1" ")
print(' ' ')
print(' \' ')
print("""line1 # print multi-line at the same time
line2
line3""")
print(""" 8888888888 888 88888
88 88 88 88 88 88
8888 88 88 88 88888
88 88 888888888 88 88
88888888 88 88 88 88 888888
88 88 88 888 88888 888888
88 88 88 88 88 88 88 88
88 8888 88 88 88 88888 8888
888 888 888888888 88 88 88
88 88 88 88 88 88888888""")
print('''|\\_/|
|q p| /}
( 0 )"""\\
|"^"` |
||_/=\\\\__|''')
print("""\ /\\
) ( ')
( / )
\\(__)|""")
print(""" /~\\
( oo|
_\\=/_
/ _ \\
//|/.\\|\\\\
|| \\ / ||
============
| |
| |
| |""")
print(""". . .
| | _ | _. _ ._ _ _
|/\\|(/.|(_.(_)[ | )(/.""")
print("""SHIP NAME CLASS DEPLOYMENT IN SERVICE
N2 Bomber Heavy Fighter Limited 21
J-Type 327 Light Combat Unlimited 1
NX Cruiser Medium Fighter Limited 18
N1 Starfighter Medium Fighter Unlimited 25
Royal Cruiser Light Combat Limited 4 """)
print(""" _.-;;-._
'-..-'| || |
'-..-'|_.-;;-._|
'-..-'| || |
'-..-'|_.-''-._|""")
BJ_10170 NFC West vs North (Bronze V)
print("""NFC West W L T
-----------------------
Seattle 13 3 0
San Francisco 12 4 0
Arizona 10 6 0
St. Louis 7 9 0
NFC North W L T
-----------------------
Green Bay 8 7 1
Chicago 8 8 0
Detroit 7 9 0
Minnesota 5 10 1
""")
1 # int
1.5 # float
"A" # str
print(type(123))
print(type("abcde"))
print(type(12.3))
print(type("12345"))
print(type(123.0))
print(type([1,2,3]))
print(type(True))
print(type(['a', 'b', 'c']))
print(type(12 + 12.3))
print(type("abcde" * 2))
input() # Always string
a = int(input()) # convert to string
int(4 ** 0.5) # 2 (float → int)
int(2.6) # 2 (float → int)
float(1) # 1.0
print(int("1") + int("1")) # 2
print(type(input())) # input : abc
print(type(float(input()))) # input : 25.5
print(type(float(input()))) # input : 25.5
a = input().split(); print(type(a)) # input : 2 3
a, b, c = input().split(); print(type(b)) # input : 1 2 3
h, i = input().split(); print(type(h)) # input : ab cd
j, k = map(float, input().split()); print(type(k)) # input : 1.2 3.3
print(type(int(input()))) # input : 1234
print(type(input())) # input : hello
print(type(float(input()))) # input : 1234.5
o, p = map(int, input()); print(type(o)) # 12
Adding and subtracting negative numbers
Subtracting a negative = adding a positive
How to solve one-step equation
a= 'Python'
b= 'World'
print('xxx')
print(float(3))
print(hello)
print('sun'+"flower")
print(a+b)
print(b+5)
print('a+b')
print(int(3.9)+float(4))
print(int(a))
print(a+'3')
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
print((a + b + c + d + e))
a, b = map(int, input().split())
print(a + b)
a, b, c = map(int, input().split())
print(a + b + c)
a = int(input())
b = int(input())
print(a + b)
BJE_13985 Equality (Bronze IV)
st = input().split()
if int(st[0]) + int(st[2]) == int(st[4]):
print('YES')
else:
print('NO')
a, b, c, d = input().split()
print(int(a + b) + int(c + d))
24 + 9
26 - 8
42 + 7
39 + 17
43 - 26
117 + 19
192 - 15
174 + 81
205 + 87
314 - 67
x+5=23
x-5=12
6+x=92
-5+x=40
x+4=10
x-14=-4
x-(-11)=15
x+24=45
x-54=123
2+x=10+2x
a, b = map(int, input().split())
print(a - b)
a, b = map(int, input().split())
print(b - a, b)
BJ_18108 1998년생인 내가 (Bronze V)
print(int(input()) - 543)
a, b, c, d, e, f = map(int, input().split())
print(1 - a, 1 - b, 2 - c, 2 - d, 2 - e, 8 - f)
a = int(input())
print(a-1946)
첫 줄에 a, 둘째 줄에 b가 주어진다. a + b 를 출력하라.
a = int(input())
b = int(input())
print(a + b)
체스에는 킹, 퀸은 1개, 룩, 비숍, 나이트는 2개, 폰은 8개가 있다.
다음 줄에 킹, 퀸, 룩, 비숍, 나이트, 폰의 개수가 주어질 때, 더 필요한 개수를 한줄로 각각 출력하라. (빼야 한다면 -)
ex)
input
2 1 2 2 2 7
output
-1 0 0 0 0 1
a, b, c, d, e, f = map(int, input().split())
print(1 - a, 1 - b, 2 - c, 2 - d, 2 - e, 8 - f)
5*7
0*2
231*3
각 상자에 5개의 연필이 있을때, 6상자에 담긴 총 연필 개수
23*4
9*5
-2*-2
7*3
3*9
2*2*4
23MH_Multiply | Variable(edit)
3 × 5 × 6
7 × 9 × 3
6 × 5 × 2
8 × 4 × 9
7 × 7 × 7
6 × 8 × 9
2 × 4 × 6
6 × 8 × 7
8 × 8 × 7
6 × 9 × 2
Multiplication 2: The multiplication tables
Why a negative times a negative is a positive
Why a negative times a negative makes intuitive sense
#
# Times 0 is 0
# Distributive property
# Thus answer is -3
print(2 * 2) # 4
print('5' * ‘5’) # Error
print('5' * 5) # 55555
print(2 + 2 * 2) # 6
print((2 + 2) * 2) # 8
a += 2; print(a)
print(a + 5)
a -= 3; print(a)
print(a + 3);
a -= 3; print(a)
print(a * 5);
a = 3 + a * 2; print(a)
a -= 3 + a; print(a)
print(a - 2);
a *= 3; print(a)
a = 0
print(a); a *= 2 # 0
print(a); a += 1 # 0
print(a); a -= 3 # 1
print(a + 3); # 1
print(a); a -= 3 # -2
print(a * 5); # -25
print(a); a = 3 + a * 2 # -7
print(a); a -= 3 + a # -7
print(a - 2); # -5
print(a); a *= 3 # -3
a, b = map(int, input().split())
print(a * b)
a, b = map(int, input().split())
print(a * b)
a = int(input())
print(a * 4)
a = int(input())
b = int(input())
print(a + b)
print(a - b)
print(a * b)
a, b = map(int, input().split())
print((a+b)*(a-b))
a, b = map(int, input().split())
print((2 * b) - a)
BJ_2845 파티가 끝나고 난 뒤 (Bronze V)
w, h = map(int, input().split())
a, b, c, d, e = map(int, input().split())
r = w * h
print(a - r, b - r, c - r, d - r, e - r)
x, y = map(int, input().split())
print(x * (y - 1) + 1)
a, b = map(int, input().split())
print(a * b - 1)
a, b, c 는 모두 정수이다.
(a + c) / 2 = b 이다.
a, b가 주어졌을때 c의 값을 구하여라.
a, b = map(int, input().split())
print((2 * b) - a)
a, b, c 는 모두 정수이다.
ceil(c / a) = b 이다. ⇒ ceil(1) = 1, ceil(1.1) = 2, ceil(0.9) = 1
a, b가 주어졌을때 c의 최솟값을 구하여라.
a, b = map(int, input().split())
print((b - 1) * a + 1)
Introduction to division with partial quotients
Dividing numbers: intro to long division
Two-variable linear equations and their graphs
print(24 // 5) # 4
print(-5 % 3) # 1
print(5 % 2) # 1
print(5.1 % 1) # 0.1
24ME_quotient|remainder (edit)
x - 4 = 9
x * 3 = 18
x // 7 = 14
x + 15 = -9
x * (-2) = -6
x // 4 - 6 = 13
x*9 +13 = -5
99 - x * 3 = 42
78 + x // 4 = 54
100 + x * (6 - 9) = 1
a, b = map(int, input().split())
print(a+b,a-b,a*b,a//b,a%b,sep='\n')
a = int(input())
print((a + 4) // 5)
ax, ay, az = map(int, input().split())
cx, cy, cz = map(int, input().split())
print(cx - az, cy // ay, cz - ax)
n,t,c,p=map(int,input().split())
print((n-1)//t*c*p)
BJ_14924 폰 노이만과 파리 (Bronze IV)
a, b, c = map(int, input().split())
print(c // (a * 2) * b)
a, b = map(int, input().split())
print(a * b // 2)
n = int(input())
print((n // 2 + 1) * (n - n // 2 + 1))
Alice 는 은퇴 후에 Bob 보다 돈이 많았으면 좋겠다.
첫줄에 Bob이 일을 시작 하는 나이, 은퇴하는 나이, 연봉, Alice가 일을 시작하는 나이, Alice의 연봉이 주어진다.
이 때 Alice가 은퇴를 해야되는 나이를 출력하라.
a, b, c, d, e = map(int, input().split())
print(d + (b - a) * c // e + 1)
24CE_Quotient | Remainder(edit)
print(1 // 2) # 0
print(5 // 3) # 1
print(5 + 3 // 2) # 6
print(0 // 0) # ERROR
print((18 - 4) % 3) # 3.0
print(2 // 2 * (2 + 2)) # 4
print(1 // 0) # ERROR
print(-6 // 3) # -2
print(-6 // -3) # 2
print(9999999 % 2) # 1
24CH_quotient|remainder (edit)
print(119 // 17)
print((-98) // 7)
print(20 // 4 - 15)
print(1938 % 7)
print(119 % 17)
print((-98) % 7)
print(1004 % 11)
print(1938 // 7)
print((18 - 4) % 3)
print((6 + 109) // 5)
a, b = map(int, input().split())
print(a // b)
print(a % b)
print(c // (a * 2) * b)
a = int(input())
print(a % 20000303)
A, B, C = map(int, input().split())
print((A + B) % C)
print((A % C + B % C) % C)
print(A * B % C)
print((A % C) * (B % C) % C)
a = int(input())
b = int(input())
c = int(input())
d = int(input())
print((a + b + c + d) // 60)
print((a + b + c + d) % 60)
a, b, c = map(int, input().split())
print(c // b, c % b)
a=int(input())
b=int(input())
print(a*(b%10),a*((b//10)%10),a*(b//100),a*b)
a, b = map(int, input().split())
c = int(input())
m = (a * 60 + b + c) % 1440
print(m // 60, m % 60)
h, m, s = map(int, input().split())
total = h * 3600 + m * 60 + s + int(input())
print(total % (24 * 3600) // 3600, total % 3600 // 60, total % 60)
Examples relating multiplication to division
Unknowns with multiplication and division
Q.
Q.
Q.
Dividing positive and negative numbers
Unknowns with multiplication and division
Why dividing by zero is undefined
Q.
Dividing positive and negative numbers
Q. Negative division
Adding fractions with unlike denominators
52+x=134
y-14=-6
x*34=17
12*x=144
x/7=20
-4/x=2
2*3*x=30
x-21=12
-9*x=81
34*x=0
BJ_16648 Accumulator Battery (Bronze IV)
t,p=map(int,input().split())
p+=min(20,p)
print(t*p/(120-p))
1 마일은 1000 * 5280 / 4854 페이스이다. 마일이 주어졌을 때 페이스를 출력하라. (소수점은 반올림 한다)
n = float(input())
print(int(n * 5280000/4854 + 0.5))
print(2 > 3)
print(-7 >= -6)
print(-15 < -13)
print("AAA" == "AAAA")
print(43 != 431)
print("a" < "b")
print("abcd" < "zyxw")
print("ab" <= "bc")
print("9999" > "10000")
print("2a5a" <= "2b5a")
print(ord('B')-ord('A'))
print(ord('z')-ord('A'))
print(ord('z')-ord('a'))
print(ord('v')-ord('e'))
print(chr(ord('C')+32))
print(chr(ord('a')+10))
print(ord('x')-ord('X'))
print(ord('R')-ord('q'))
print(chr(65+40))
print(chr(122-20))
print(ord(input()))
print(ord(input()) + 1 - ord("가"))
print(chr(ord('가') + int(input()) - 1))
a=[0]*26
for x in input():
a[ord(x)-97]+=1
print(*a)
tel = input()
delay = 0
data = [3,3,3,4,4,4,5,5,5,6,6,6,7,7,7,8,8,8,8,9,9,9,10,10,10,10]
for c in tel:
delay += data[ord(c)-65]
print(delay)
for _ in range(int(input())):
a, b = input().split()
li = []
for i in range(len(a)):
li.append((ord(b[i])-ord(a[i]))%26)
print("Distances:", *li)
st = input()
for ch in st:
if ch <= 'C':
print(chr(ord(ch) + 23), end='')
else:
print(chr(ord(ch) - 3), end='')
a = 5
b = 3
print(1 if a == b else 2)
print(1 if a > b else 2)
print(1 if a == 4 and b == 3 else 2)
print(1 if a >= 0 or b < -1 else 2)
print(1 if all([a > 5, b < 5]) else 2)
print(1 if a > 10 else 2 if b < 10 else 3)
print(1 if len(a) == 1 else 2)
print(10 if a // b == 1 else 20)
print(1 if a % 2 == 0 else 2 if b % 2 ==0 else 3)
print(1 if ord('a') > a else 2 if ord('b') < b else 3)
BJ_17903 Counting Clauses (Bronze IV)
a, b= map(int, input().split())
if a >= 8:
print("satisfactory")
else:
print("unsatisfactory")
a = int(input())
if a == 0:
print('YONSEI')
else:
print('Leading the Way to the Future')
print('YONSEI' if input() == '0' else 'Leading the Way to the Future')
a, b = map(int, input().split())
if b < 0:
print(a // b + 1)
print(a % b - b)
else:
print(a // b)
print(a % b)
A, B, C = map(int, input().split())
if C <= B:
print(-1)
else:
print(A // (C - B) + 1)
a, b = map(int, input().split())
print(1 if a == b else 0)
a, b = map(int, input().split())
if a == b:
print(1)
else:
print(0)
a, b, c, d, e = int(input()), int(input()), int(input()), int(input()), int(input())
if a > 0:
print(e * (b - a))
else:
print((-a * c) + d + e * b)
n = int(input())
if n % 10 != 0:
print(-1)
else:
print(n // 300, n % 300 // 60, n % 60 // 10)
BJE_6778 Which Alien? (Bronze IV)
a, e = int(input()), int(input())
if a >= 3 and e <= 4:
print('TroyMartian')
if a <= 6 and e >= 2:
print('VladSaturnian')
if a <= 2 and e <= 3:
print('GraemeMercurian')
BJ_14038 Tournament Selection (Bronze IV)
w = 0
for _ in range(6):
if input() == 'W':
w += 1
if w == 0:
print(-1)
elif w <= 2:
print(3)
elif w <= 4:
print(2)
else:
print(1)
BJE_15080 Every Second Count (Bronze IV)
a, b, c = map(int, input().split(" : "))
d, e, f = map(int, input().split(" : "))
time = (d-a) * 3600 + (e - b) * 60 + f - c
if(time < 0):
time += 24 * 3600
print(time)
BJE_17009 Winning Score (Bronze IV)
apple = banana = 0
apple += int(input()) * 3
apple += int(input()) * 2
apple += int(input())
banana += int(input()) * 3
banana += int(input()) * 2
banana += int(input())
if apple < banana:
print('B')
elif apple == banana:
print('T')
else:
print('A')
h, m = map(int, input().split())
m = h * 60 + m - 45
if m < 0:
m += 1440
print(m // 60, m % 60)
A, B = map(int, input().split())
if A > B:
print('>')
elif A < B:
print('<')
else:
print('==')
score = int(input())
if score >= 90:
print('A')
elif score >= 80:
print('B')
elif score >= 70:
print('C')
elif score >= 60:
print('D')
else:
print('F')
A = int(input())
B = int(input())
C = int(input())
if A + B + C != 180:
print("Error")
elif A == B == C:
print("Equilateral")
elif A == B or B == C or A == C:
print("Isosceles")
else:
print("Scalene")
BJ_19944 뉴비의 기준은 뭘까? (Bronze IV)
a, b = map(int, input().split())
if b < 3:
print('NEWBIE!')
elif b <= a:
print('OLDBIE!')
else:
print('TLE!')
BJE_6764 Sounds Fishy! (Bronze IV)
a=int(input())
b=int(input())
c=int(input())
d=int(input())
if a<b<c<d:print('Fish Rising')
elif a>b>c>d:print('Fish Diving')
elif a==b==c==d:print('Fish At Constant Depth')
else:print('No Fish')
a, b, c = map(int, input().split())
if a + b == c:
print(f"{a}+{b}={c}")
elif a - b == c:
print(f"{a}-{b}={c}")
elif a * b == c:
print(f"{a}*{b}={c}")
elif a // b == c:
print(f"{a}/{b}={c}")
elif a == b + c:
print(f"{a}={b}+{c}")
elif a == b - c:
print(f"{a}={b}-{c}")
elif a == b * c:
print(f"{a}={b}*{c}")
elif a == b // c:
print(f"{a}={b}/{c}")
a개의 돌이 다음과 같이 1열로 나열되어 있다.
1 2 3 … a
Alice 와 Bob 이 번갈아 가며 2개의 연속된 번호의 돌을 가져간다.
더 이상 가져갈 수 있는 돌이 없을때, 남은 돌의 개수가 홀수이면 Alice가 이기고 짝수면 Bob이 이긴다.
예를들어 돌 1 2 3 4 로 시작해 Alice 가 2, 3 을 가져가면 Bob은 더 이상 가져갈 수 있는 연속된 돌이 없고,
남은 돌의 개수는 1, 4, 총 2개이므로 Bob이 승리한다.
Alice가 항상 먼저 시작 가져가고 두 명은 항상 최적의 수를 둔다.
a가 주어질때 승자를 구하여라.
[Simp] a 가 짝수이면 Bob 홀수이면 Alice를 출력하라.
# Alice와 Bob 이 2개를 여러번 가져가도 남은 돌의 개수의 parity(짝, 홀)은 변하지 않는다.
a = int(input())
if a % 2 == 1:
print("Alice")
else:
print("Bob")
a = 10
print(True and False)
print(True or False)
print( a % 2 == 0 )
print( a // 2 != 0 and a * 3 = 9 )
print( a == 9 or a == 10 )
print(all([True, False, False, True])
print(any([True, False, False, True]))
print(all([True, True, True False]))
print(all([True, any([False, True])]))
a = int(input())
b = int(input())
if a > 0 and b > 0:
print(1)
elif a < 0 and b > 0:
print(2)
elif a < 0 and b < 0:
print(3)
else:
print(4)
BJ_17362 수학은 체육과목 입니다2 (Bronze IV)
turn = int(input()) % 8
if turn == 1:
print(1)
elif turn == 2 or turn == 0:
print(2)
elif turn == 3 or turn == 7:
print(3)
elif turn == 4 or turn == 6:
print(4)
elif turn == 5:
print(5)
a, b, c = map(int, input().split())
if a + b + c >= 100:
print("OK")
elif a < b and a < c:
print("Soongsil")
elif b < a and b < c:
print("Korea")
else:
print("Hanyang")
n = int(input())
if n % 4 == 0 and (n % 100 != 0 or n % 400 == 0):
print(1)
else:
print(0)
a, b, c = map(int, input().split())
if a == b == c:
print(10000 + a * 1000)
elif a == b or a == c:
print(1000 + a * 100)
elif b == c:
print(1000 + c * 100)
else:
print(max(a, b, c) * 100)
m, d = int(input()), int(input())
if m == 1 or m == 2 and d < 18:
print('Before')
elif m == 2 and d == 18:
print('Special')
else:
print('After')
sm, df = map(int, input().split())
a = sm - (sm + df) // 2
b = (sm + df) // 2
if (sm + df) % 2 != 0 or a < 0 or b < 0:
print(-1)
elif a > b:
print(a, b)
else:
print(b, a)
input 이 OCT 31 이거나 DEC 25 일 시 'yup' 그렇지 않으면 'nope' 를 출력한다
s = input()
if s == 'OCT 31' or s == 'DEC 25':
print('yup')
else:
print('nope')
a, b = map(int, input().split())
c, d = map(int, input().split())
print(min(a + d, b + c))
cur, nex = int(input()), int(input())
print(min(cur, nex + 60) * 1500 + (cur - min(cur, nex + 60)) * 3000)
a, b, c = map(int, input().split())
if a == b == c:
print(10000 + a * 1000)
elif a == b or a == c:
print(1000 + a * 100)
elif b == c:
print(1000 + c * 100)
else:
print(max(a, b, c) * 100)
n, w, h, l = map(int, input().split())
cow = (w // l) * (h // l)
print(min(cow, n))
_ = input()
li = list(map(int, input().split()))
print(min(li), max(li))
BJ_1085 직사각형에서 탈출 (Bronze III)
x, y, w, h=map(int,input().split())
print(min(x, y, w - x, h - y))
BJ_16917 양념 반 후라이드 반 (Bronze III)
a, b, c, x, y = map(int, input().split())
v = 0
if x > y:
v = 2 * c * y + a * (x - y)
else:
v = 2 * c * x + b * (y - x)
print(min(a*x + b*y, 2 * c * max(x, y), v))
a = -5
b = 3
print(abs(a))
print(abs(a*b))
print(min(1,2,3,4,5))
print(min(-10, -5, 0, 5, 10))
print(max(a,b))
print(abs(min(a,b)))
print(max([6, -10, 1, 3]))
print(min('a, 'c',’e’))
print(min(True, False))
a, b = map(int, input().split())
print(abs(a - b))
N, M, K = map(int, input().split())
print(min(M, K) + N - max(M, K))
a, b, c = map(int, input().split())
print(max(a * b // c, int(a / b * c)))
print(max(a * b // c, a * c // b))
a, b, c, d = map(int, input().split())
e, f, g, h = map(int, input().split())
print(max(a + b + c + d, e + f + g + h))
a = max(40, int(input()))
b = max(40, int(input()))
c = max(40, int(input()))
d = max(40, int(input()))
e = max(40, int(input()))
sum = (a+b+c+d+e) // 5
print(sum)
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
f = int(input())
print(a + b + c + d + e + f - min(a, b, c, d) - min(e, f))
a = int(input())
b = int(input())
c = int(input())
d = int(input())
e = int(input())
X = a * e
Y = b + max(e - c, 0) * d
print(min(X, Y))
a, b, c = map(int, input().split())
print(max(0, a * b - c))
a, b = map(int, input().split())
c, d = map(int, input().split())
e, f = map(int, input().split())
x = max(abs(e - a), abs(f - b))
y = abs(e - c) + abs(f - d)
if x == y:
print('tie')
elif x < y:
print('bessie')
else:
print('daisy')
BJ_1598 꼬리를 무는 숫자 나열 (Bronze III)
a, b = map(int, input().split())
a -= 1
b -= 1
print(abs(a // 4 - b // 4) + abs(a % 4 - b % 4))
a, b = map(int, input().split())
ra = (a % 10) * 100 + (a // 10 % 10) * 10 + (a // 100)
rb = (b % 10) * 100 + (b // 10 % 10) * 10 + (b // 100)
print(max(ra, rb))
정수 a, b, c 가 주어진다. 한 변의 길이가 a이고 높이가 4인 정사각형의 케익이 있다.
가로로 b, 세로로 c의 위치에서 케익을 자른다. 이때 가장 큰 조각의 부피를 구해라.
a, b, c = map(int, input().split())
print(max(a - b, b) * max(a - c, c) * 4)
두 주사위에 a와 b개의 면이 있다. 이때 두 주사위를 굴렸을 때 가장 높은 확률로 나오는 합을 출력하라.
a, b = map(int, input().split())
for i in range(min(a, b) + 1, max(a, b) + 2):
print(i)
왼쪽과 오른쪽의 뿔의 개수가 주어진다.
왼쪽과 오른쪽의 뿔의 개수가 같을 때 → Even 총_뿔수
다를 시 → Odd 더_많은_뿔수 * 2
뿔이 하나도 없을 시 → Not a Moose를 출력한다.
a, b = map(int, input().split())
if a == b == 0:
print("not a moose")
elif a == b:
print(f"Even {a * 2}")
else:
print(f"Odd {max(a, b) * 2}")
1부터 100까지 연속된 n개의 수를 뽑는다.
이 때 수의 합이 짝수이면 Even 홀수이면, Odd, 둘다 가능하면 Either을 출력하라.
n = int(input())
if n % 4 == 0:
print('Even')
elif n % 2 == 0:
print('Odd')
else:
print('Either')
첫줄에 a, b, c, d가 주어진다.
이는 각각 easy, medium, hard, total문제 개수 이다.
easy, medium, hard를 모두 포함하고, 총 문제 수가 total인 문제집을 만들 수 있으면 YES 아니면 NO를 출력하라.
a, b, c, d = map(int, input().split())
if a == 0 or b == 0 or c == 0 or a + b + c < d or d < 3:
print("NO")
else:
print("YES")
a, b는 0이 포함되지 않은 3자리 정수이다.
a, b 의 숫자를 뒤집었을 때, ⇒ 426 를 뒤집으면 624
뒤집혀진 a, b중 큰 수를 구하라.
a, b = map(int, input().split())
ra = (a % 10) * 100 + (a // 10 % 10) * 10 + (a // 100)
rb = (b % 10) * 100 + (b // 10 % 10) * 10 + (b // 100)
print(max(ra, rb))
a, b가 주어진다.
a 가 b 보다 크면 Dr. Chaz needs a - b more pieces of chicken!
b 가 a 보다 크면 Dr. Chaz will have b - a pieces of chicken left over!
를 출력하라. (이 때 차이가 1이면 s는 pieces를 piece로 대체한다.)
a, b = map(int, input().split())
if a < b:
print(f"Dr. Chaz will have {b - a} piece{'' if b - a == 1 else 's'} of chicken left over!")
else:
print(f"Dr. Chaz needs {a - b} more piece{'' if a - b == 1 else 's'} of chicken!")
a, b는 0이 아닌 정수이다.
a, b가 주어졌을때 몇 사분면(Quadrant)에 있는지 구하여라.
a = int(input())
b = int(input())
if a > 0 and b > 0:
print(1)
elif a < 0 and b > 0:
print(2)
elif a < 0 and b < 0:
print(3)
else:
print(4)
아침에 일찍 일어나고자 알람을 45분 일찍 맞춘다.
h, m이 주어지면 맞춰야 되는 알람시간 h, m을 출력하라.
h, m = map(int, input().split())
total = h * 60 + m - 45
if total < 0:
total += 1440
print(total // 60, total % 60)
a와 b가 주어진다.
b가 짝수이면 possible 홀수이면 impossible을 출력한다.
a, b = map(int, input().split())
if b % 2 == 0:
print("possible")
else:
print("impossible")
정수 m, d가 주어진다.
2009년 m월 d일이 무슨 요일인지 출력하라.
n_days = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
weeks = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday', 'Saturday', 'Sunday']
day, month = map(int, input().split())
nth = sum(n_days[:month - 1]) + day - 1
print(weeks[(nth + 3) % 7])
골드는 3, 실버는 2, 쿠퍼는 1의 값어치를 한다.
한 턴에 victory 카드와 treasure 카드 중 하나를 선택 할 수 있는데 비용은 아래와 같다.
Province (costs 8)
Duchy (costs 5)
Estate (costs 2)
Gold (costs 6)
Silver (costs 3)
Copper (costs 0)
골드 실버 쿠퍼의 개수가 주어질 때 고를 수 있는 최고의 victory or treasure 카드를 출력하라.
g, s, c = map(int, input().split())
tot = g * 3 + s * 2 + c
if tot >= 8:
print("Province or Gold")
elif tot >= 6:
print("Duchy or Gold")
elif tot >= 5:
print("Duchy or Silver")
elif tot >= 3:
print("Estate or Silver")
elif tot >= 2:
print("Estate or Copper")
else:
print("Copper")
input().split() # 띄어쓰기를 기준으로 나눔
a, b = map(int, input().split()) # 모두 숫자형으로 바꿈
Map object must be casted → to save memory
li = [1, 2, 3, 4]
def double(n):
return n * 2
list(map(lambda x : x * x, numbers)) # lambda function
a = ['1', '2', '3']
b = "5"
c = '5 10 15 20'
print(c.split())
print(c.split('0'))
print('Python'+int(b))
print(a+b)
print(b+5)
print(list(map(int, c.split())))
print(sum(map(int, a)))
print(list(map(float, a)))
print(list(map(int, a))[1])
print(list(map(int, b)))
첫 줄에 a, b가 주어진다.
b를 출력하라.
_, a = map(int, input().split())
print(a)
캥거루 a, b, c가 한 선 위에 순서대로 있다.
캥거루 a, c가 b 양옆으로 점프를 하는데, 이 때 더 긴 점프의 길이를 출력하라.
a, b, c = map(int, input().split())
print(max(c - b - 1, b - a - 1))
문장이 주어지는데, 문장에서 같은 단어가 두번 이상 등장하면 no 모든 단어가 한번 등장하면 yes를 출력하라.
li = input().split()
print("yes" if len(set(li)) == len(li) else "no")
len # find length of iterable
sum # sum of all iterables
BJ_15873 공백 없는 A+B (Bronze IV)
s = input()
if len(s) == 4:
print(20)
elif len(s) == 3:
if s[1] == '0'
print(10 + int(s[2]))
else:
print(10 + int(s[0]))
else:
print(int(s[0]) + int(s[1]))
n = list(map(int, input().split()))
print(sum(n))
N = int(input())
for _ in range(N):
n = list(map(int, input().split()))
print(sum(n))
print(sum(map(int, input().split(','))))
li = list(input().split())
print(len(li))
input()
print(sum(map(int, input())))
def solve(a):
return sum(a)
a = input()
b = input()
if len(b) > len(a):
print("no")
else:
print('go')
n = int(input())
li = list(map(int, input().split()))
print(sum(li) / max(li) * 100 / len(li))
s = input()
happy = s.count(":-)")
sad = s.count(":-(")
if happy < sad:
print("sad")
elif happy > sad:
print("happy")
elif happy == sad != 0:
print("unsure")
else:
print("none")
두 문자가 각 줄에 주어진다.
이 때 첫 문자가 길면 no 두번째 길이가 같거나, 두번째 문자가 길 때는 go를 출력하라.
a = input()
b = input()
if len(b) > len(a):
print("no")
else:
print('go')
LC151_ reverse-words-in-a-string
def reverseWords(self, s: str) -> str:
return " ".join(reversed(s.split()))
print(range(10)[2])
print(range(-10)[2])
print(range(30)[30])
print(range(10,100)[2])
print(range(-10,-100)[2])
print(range(10, 2)[1])
print(range(3,5,2)[1])
print(range(0,100,3)[10])
print(range(100,0,-10)[5])
print(range(0,-1000,10)[10])
for i in range(3):
print(1, end = ' ')
for i in range(5):
print(i, end = ' ')
for i in range(1,6,2):
print(i, end = ' ')
for i in range(5,16,4):
print(i, end = ' ')
for i in range(10, 0, -2):
print(i, end = ' ')
for i in range(0, 10, 10):
print(i, end = ' ')
for i in range(0, 10, 0):
print(i, end = ' ')
for n in range(1, 10, 2):
print(n, end = ' ')
for i in range(10, 0, -1):
print(i, end = ' ')
for i in range(0, 10, 0.5):
print(i, end = ' ')
for i in range(int(input()), 0, -1):
print(i)
a = int(input())
for i in range(1, 10):
print(f"{a} * {i} = {a * i}")
N = int(input())
for _ in range(N):
print('=' * int(input()))
n = int(input())
for i in range(1, n + 1):
print('*' * i)
n = int(input())
for i in range(1, n + 1):
print(' ' * (n - i) + '*' * i)
a = int(input())
for i in range(1,a+1):
print("*"*(a-i+1))
a = int(input())
for i in range(1,a+1):
print(" "*(i-1) + "*"*(a-i+1))
a = int(input())
for i in range(1,a+1):
b = ' '*(a-i)+'*'*((2*i)-1)
print(b)
a = int(input())
for i in range(a-1,-1,-1):
print(' '*(a-i-1)+('*'*(2*i+1)))
a = int(input())
for i in range(a-1):
print(' '*(a-i-1)+('*'*(2*i+1)))
for i in range(a-1,-1,-1):
print(' '*(a-i-1)+('*'*(2*i+1)))
a=int(input())
b=a
for i in range(1,a+1):
print('*'*(i)+' '*(2*(b-i))+'*'*(i))
for k in range(1,b+1):
print('*'*(b-k)+' '*(2*k)+'*'*(b-k))
a = int(input())
for i in range(a-1,0,-1):
print(' '*(a-i-1)+('*'*(2*i+1)))
for i in range(a):
print(' '*(a-i-1)+('*'*(2*i+1)))
a = int(input())
b = a
for i in range(1, a+1):
print(' '*(b-i)+'*'*(i))
for k in range(1,b):
print(' '*(k)+'*'*(b-k))
BJ_10990 별 찍기 - 15 (Bronze III)
N = int(input()) - 1
print (" " * N + "*")
for i in range(N):
print(" " * (N - i - 1) + '*' + ' ' * (i * 2 + 1) + '*')
a = int(input())
for i in range(1, a + 1):
print(' ' * (a - i) + '* ' * i)
for _ in range(int(input())):
a = int(input())
print("#" * a)
for _ in range(a - 2):
print("#" + "J" * (a - 2) + "#")
if a > 1:
print("#" * a)
print()
BJ_10995 별 찍기 - 20 (Bronze II)
n = int(input())
for i in range(n):
print("* " * n if i % 2 == 0 else " *" * n)
n = int(input())
for _ in range(n):
print('* ' * (n - n//2))
print(' *' * (n//2))
BJ_10950 A + B - 3 (Bronze III)
for _ in range(int(input())):
a, b = map(int, input().split())
print(a + b)
T = int(input())
for _ in range(T):
V, E = map(int, input().split())
print(2 - V + E)
for _ in range(int(input())):
a, b = map(int, input().split())
print((b * 2 - a), (a - b))
BJ_10214 Baseball (Bronze III)
for _ in range(int(input())):
yonsei = korea = 0
for _ in range(9):
a, b = map(int, input().split())
yonsei += a
korea += b
if yonsei > korea:
print('Yonsei')
elif yonsei == korea:
print('Draw')
else:
print('Korea')
moves = input()
cur = 1
for move in moves:
if move == 'A':
if cur == 1:
cur = 2
elif cur == 2:
cur = 1
elif move == 'B':
if cur == 2:
cur = 3
elif cur == 3:
cur = 2
else:
if cur == 1:
cur = 3
elif cur == 3:
cur = 1
print(cur)
n, m = map(int, input().split())
num = 0
for i in range(n):
for j in range(m):
num += 1
if j == m - 1:
print(num)
else:
print(num, end=' ')
BJ_8320 직사각형을 만드는 방법 (Bronze III)
n = int(input())
cnt = 0
for i in range(1, n + 1):
for j in range(i, n + 1):
if i * j <= n:
cnt += 1
print(cnt)
n = int(input())
total = 0
for _ in range(n):
total += int(input())
print(total - n + 1)
for i in range(3):
s = sum(int, input().split())
if s == 0:
print('D')
elif s == 1:
print('C')
elif s == 2:
print('B')
elif s == 3:
print('A')
else:
print('E')
for _ in range(int(input())):
m = int(input())
print(sum(map(int, input().split())))
c = s = 100
for _ in range(int(input())):
first, second = map(int, input().split())
if first < second:
c -= second
elif first > second:
s -= first
print(c, s, sep='\n')
cur = 0
m = 0
for i in range(4):
a, b = map(int, input().split())
total += b - a
if m < cur:
m = cur
print(m)
mx, cur = 0, 0
for _ in range(10):
leave, enter = map(int, input().split())
cur = cur - leave + enter
if mx < cur:
mx = cur
print(mx)
n = int(input())
cur = 1
for _ in range(n):
a, b = map(int, input().split())
if cur == a:
cur = b
elif cur == b:
cur = a
print(cur)
k= int(input())
ret=1
for i in range(1,k+1):
ret = ret*i
print(ret)
a = int(input())
for _ in range(9):
a -= int(input())
print(a)
sm = 0
mn = 100
for _ in range(7):
a = int(input())
if a % 2 == 1:
mn = min(mn, a)
sm += a
if mn == 100:
print(-1)
else:
print(sm)
print(mn)
BJ_10886 0 = not cute / 1 (Bronze III)
a=int(input())
b=0
for i in range(a):
b=b+int(input())
if b>(a//2):
print("Junhee is cute!")
else:
print("Junhee is not cute!")
num = mx = 0
for i in range(5):
temp = sum(map(int, input().split()))
if (mx < temp):
mx = temp
num = i + 1;
print(num, mx)
for _ in range(int(input())):
h,w,n = map(int,input().split())
print(str((n-1)%h+1) + str((n-1)//h+1).rjust(2, '0'))
BJ_2547 사탕 선생 고창영 (Bronze III)
N = int(input())
li = [int(input()) for _ in range(N)]
for m in li:
for t in [25, 10, 5, 1]:
print(m // t, end = ' ')
m %= t
print()
mx = 0
for _ in range(int(input())):
a, b, c = map(int, input().split())
if a == b == c:
mx = max(mx, 10000 + a * 1000)
elif a == b or a == c:
mx = max(mx, 1000 + a * 100)
elif b == c :
mx = max(mx, 1000 + b * 100)
else:
mx = max(mx, max(a, b, c) * 100)
print(mx)
for _ in range(int(input())):
n, c = map(int, input().split())
print((n - 1)//c + 1)
A, B = map(str, input().split())
digit_A = 0
digit_B = 0
for a in A:
digit_A += int(a)
for b in B:
digit_B += int(b)
print(digit_A * digit_B)
N = int(input())
for _ in range(N):
a, b = map(int, input().split(','))
print(a + b)
N = int(input())
for _ in range(N):
if int(input()) % 2 == 0:
print("even")
else:
print("odd")
N = int(input())
for _ in range(N):
st = input()
score, row = 0, 0
for ch in st:
if ch == 'X':
row = 0
else:
row += 1
score += row
print(score)
a, b = 1, 0
for i in range(int(input())):
a, b = b, a + b
print(a, b)
N, score, p = map(int, input().split())
if N == 0:
print(1)
exit()
li = list(map(int, input().split()))
if len(li) >= p and li[p - 1] >= score:
print(-1)
else:
li += [-1]
for i in range(p):
if li[i] <= score:
print(i + 1)
break
첫줄에 N이 주어지고 N줄에 b,p가 차례로 주어진다
ABPM최솟값, BPM값, ABPM최댓값을 한 줄에 출력하라.
(BPM은 60b/p로 계산)
n_test = int(input())
for _ in range(n_test):
beat, sec = map(float, input().split())
print((beat - 1) / sec * 60, beat / sec * 60, (beat + 1) / sec * 60)
처음에는 1번에 구슬이 놓여있고 ABC는 위와 같이 정의 된다.
주어진 인풋과 같이 돌을 옮겼을때 최종적인 돌의 위치를 출력하라.
moves = input()
cur = 1
for move in moves:
if move == 'A':
if cur == 1:
cur = 2
elif cur == 2:
cur = 1
elif move == 'B':
if cur == 2:
cur = 3
elif cur == 3:
cur = 2
else:
if cur == 1:
cur = 3
elif cur == 3:
cur = 1
print(cur)
첫줄에 N이 주어진다.
다음 줄에 N개의 숫자가 주어지는데, 이 때 0보다 작은 수의 절대값의 합을 구하여라.
N = int(input())
ret = 0
for a in map(int, input().split()):
if a < 0:
ret -= a
print(ret)
pa, pb = None, None
ret = 0
for _ in range(int(input())):
a, b = map(float, input().split())
if pa != None:
ret += (a - pa) * (b + pb) / 2 / 1000
pa, pb = a, b
print(ret)
첫 줄에 N, w, h이 주어진다.
다음 N줄에 성냥의 길이가 주어지는데 이때 가로 세로가 w, h 인 상자에 들어가면 DA, 들어가지 않으면 DE를 출력하라.
n_match, w, h = map(int, input().split())
mx = (w ** 2 + h ** 2) ** 0.5
for _ in range(n_match):
x = int(input())
if x <= mx:
print('DA')
else:
print('NE')
BJ_14656 조교는 새디스트야!! (Bronze III)
n = int(input())
students = list(map(int, input().split()))
res = 0
for i, s in enumerate(students):
if s != i + 1:
res += 1
print(res)
주어진 문자를 PERPERPER로 바꾸는데 몇 번 문자를 바꿔야 하는가?
st = input()
ret = 0
for i, ch in enumerate(st):
if i % 3 == 0 and ch != 'P':
ret+=1
if i % 3 == 1 and ch != 'E':
ret+=1
if i % 3 == 2 and ch != 'R':
ret+=1
print(ret)
li = [1, 2, 0 6]
li[i] # element in ith index
a = "abcdefg"
print(a[:3]) # abc
a = "abcde"
b = "zxyb"
print(a[0])
print(b[5])
print(a[2] + b[1])
print(b[0]*3)
print((a[1]+b[3])*2)
print(a[3],b[1])
print(a[:4])
print(b[2:])
print(b[-4])
print(a[:-3]+b[-2:])
a = input()
if a[:3] == "555":
print("YES")
else:
print("NO")
p = list(map(int, input.split()))
print(min(p[:3]) + min(p[3:]) - 50)
for _ in range(int(input())):
s = input().rstrip()
print(s[0], s[-1], sep='')
for _ in range(int(input())):
a, b = input().split()
print(b[:int(a) - 1]+b[int(a):])
BJ_11721 열 개씩 끊어 출력하기 (Bronze II)
st = input()
for i in range(len(st) // 10 + 1):
print(st[i * 10: (i + 1) * 10])
m = [31,28,31,30,31,30,31,31,30,31,30,31]
t = ['SUN','MON','TUE','WED','THU','FRI','SAT']
a, b = map(int, input().split())
print(t[(b + sum(m[:a - 1]))%7])
첫줄에 N이 주어진다.
다음 N줄에 문자가 주어지는데, Simon says로 시작 할 시에, 이후에 나오는 행동을 출력하라.
N = int(input())
for _ in range(N):
s = input()
if s[:10] == "Simon says":
print(s[10:])
띄어쓰기 없이 같은 문자를 3번 보내는데 그중 하나는 오타이다. 원래 보내려는 문자를 출력하라.
s = input()
chunk = len(s) // 3
a = s[:chunk]
b = s[chunk:chunk * 2]
c = s[chunk * 2:]
if b == c:
print(b)
else:
print(a)
# Number
{3.1415:.2f} # 3.14 (decimal places)
print(f'{3.1415:+.2f}') # +3.14 (decimal places + sign)
{5:0>2d} # 05 (left padding)
{5:x<4d} # 5xxx (right padding)
{5:x^4d} # xx5xx (center padding)
{1000000:,} # 1,000,000 (comma separator)
{1000000000:.2e} # 1.00e+09 (Exponent notation)
{0.35:.3%} # 35.000% (Percent)
a = 5
b = 3
print(f'{10/0:.1f}')
print(f'{4/3:.1f}')
print(f'{5/3:.3f}')
print(f'{4/8:.2f}')
print(f'{-3/2:.5f}')
print(f"{a}+{b} = {a+b}")
print(f"{a}*{b} = {a*b}")
print(f"{a} is five")
print("{'version'} : {b}")
print(f"{'version'} : {b}")
N = int(input())
for _ in range(N):
price = float(input())
print(f"${price * 0.8:.2f}")
for i in range(1, int(input()) + 1):
a, b = map(int, input().split())
print(f"Case #{i}: {a + b}")
n_test = int(input())
for i in range(1, n_test + 1):
a, b = map(int, input().split())
print(f"Case #{i}: {a} + {b} = {a + b}")
for i in range(int(input())):
s = list(map(int, input().split()))
print(f'Case {i+1}: {sum(s)}')
BJ_9316 Hello Judge (Bronze III)
n = int(input())
for i in range(1, n + 1):
print(f"Hello World, Judge {i}!")
for _ in range(int(input())):
a, b = map(int, input().split())
print(f'You get {a//b} piece(s) and your dad gets {a%b} piece(s).')
BJ_5361 전투 드로이드 가격 (Bronze III)
for _ in range(int(input())):
a, b, c, d, e = map(int, input().split())
total = a * 350.34 + b * 230.90 + c * 190.55 + d * 125.30 + e *180.90
print('$%.2f' %total)
n = int(input())
print(f'{2**(-n):.{n}f}')
q1 = q2 = q3 = q4 = axis = 0
N = int(input())
for _ in range(N):
x, y = map(int, input().split())
if x == 0 or y == 0:
axis += 1
elif x > 0 and y > 0:
q1 += 1
elif x < 0 and y > 0:
q2 += 1
elif x < 0 and y < 0:
q3 += 1
elif x > 0 and y < 0:
q4 += 1
print(f"Q1: {q1}")
print(f"Q2: {q2}")
print(f"Q3: {q3}")
print(f"Q4: {q4}")
print(f"AXIS: {axis}")
a, b = int(input()), int(input())
a //= 100
for n in range(b):
if (a * 100 + n) % b == 0:
print(f'{n:02d}')
n, k = map(int, input().split())
a = list(map(int, input().split(",")))
for _ in range(k):
a = [a[i+1]-a[i] for i in range(len(a)-1)]
print(*a, sep=",")
첫 줄에는 N이 주어진다.
다음 N줄에
1 Abracadabra
…
N Abracadabra
을 출력하라
n_line = int(input())
for i in range(1, n_line + 1):
print(f"{i} Abracadabra")
s = int(input())
print(f"{s}:")
for n in range(2, s // 2 + 2):
if (s - n) % (2 * n - 1) == 0 or s % (2 * n - 1) == 0:
print(f"{n},{n - 1}")
if s % n == 0:
print(f"{n},{n}")
li = [1, 2, 3, 4]
[n * 10 for n in li] # 10, 20, 30, 40
[i for i in range(30) if i % 3 == 0] # [0, 3, 6, 9, 12, 15, 18, 21, 24, 27]
lis = [[1, 2, 3], [4, 5], [6, 7, 8, 9]]
flattened = [el for li in lis for el in li]
print(f"{a}=5" if a == 5 else f"{a}!=5 ")
print(f"{a}=={b}" if a == b else f"{a} != {b}")
44CH_format|comprehension(edit)
li = [2, 5, 3]
print([i for i in range(3)])
print([i for i in range(5) if i % 2 == 0])
print([i + j for i in range(3) for j in range(3)])
print([n for n in li])
print([n*5 for n in li])
print([n for n in li if n % 2 != 0])
print([i * n for i in li for n in li])
print([i * n for i in li for n in range(3)])
print([i * n for i in li for n in range(5) if n % 2 != 0])
print([i // n for i in range(1,4) for n in range(1,4)])
BJE_19602 Dog Treats (Bronze IV)
a = int(input())
b = int(input())
c = int(input())
print('sad' if a + 2 * b + 3 * c < 10 else 'happy')
BJ 15780 멀티탭 충분하니? (Bronze III)
n, k = map(int, input().split())
c = list(map(int, input().split()))
result = 0
for cc in c:
result += (cc + 1) // 2
print('YES' if result >= n else "NO")
BJ 18247 겨울왕국 티켓 예매 (Bronze III)
T = int(input())
for _ in range(T):
n, m = map(int, input().split())
if m < 4 or n < 12:
print(-1 if m < 4 or n < 12 else 11 * m + 4)
input()
y = m = 0
for p in map(int,input().split()):
y+=p//30*10+10
m+=p//60*15+15
print('M' if y>m else 'Y' if y<m else 'Y M',min(y,m))
N = int(input())
for _ in range(N):
input()
line = int(input())
li = [int(input()) for _ in range(line)]
print("YES" if sum(li) % len(li) == 0 else "NO")
N = int(input())
for _ in range(N):
evens = [n for n in list(map(int, input().split())) if n % 2 == 0]
print(sum(evens), min(evens))
BJ_5597 과제 안 내신 분..? (Bronze II)
a = [int(input()) for _ in range(28)]
for i in range(1, 31):
if i not in a:
print(i)
for _ in range(int(input())):
k = int(input())
n = int(input())
people = list(range(n + 1))
for i in range(k):
for j in range(1, n + 1):
people[j] = people[j] + people[j - 1]
print(people[-1])
N = int(input())
A = map(int, input().split())
B, C = map(int, input().split())
print(sum(((a-B-1) // C) + 1 if a >= B else 0 for a in A) + N)
N = int(input())
for i in range(N):
li = list(map(int, input().split()))
av = sum(li[1:]) / li[0]
print(f"{len([x for x in li[1:] if x > av]) / li[0]:.3%}")
append() # Adds an element at the end of the list
clear() # Removes all the elements from the list
copy() # Returns a copy of the list
count() # Returns the number of elements with the specified value
extend() # Add the elements of a list (or any iterable), to the end of the current list
index() # Returns the index of the first element with the specified value
insert() # Adds an element at the specified position
pop() # Removes the element at the specified position
remove() # Removes the first item with the specified value
reverse() # Reverses the order of the list
sort() # Sorts the list
a = [1, 2, 3, 4, 5]
b = [4, 5, 6, 7, 8]
a.append(99); print(a[-1])
b.remove(8); print(b[-1])
print(a.pop())
print(a[1])
b.pop(); print(len(b))
a.append('xz'); print(a[-1])
b.append(10); print(b[-1])
a[3] = 77; print(a[3])
print(a[0], b[-1])
print(b[4], a[-5])
a = [1, 1, 1, 10, 20, 30]
b = ['aaa', 'w', 'x', 'xyz']
print(a.index(30))
print(b.index('aaa'))
print(sum(a))
print(b.count('x'))
print(b[1].count('a'))
print(a.count(1))
a.insert(-2, 53); print(a[4])
b.insert(4, 'th'); print(b[-1])
print(len(a + b))
print(list('abcd')[1])
BJE_11549 Identifying tea (Bronze IV)
a = input()
print(input().split().count(a))
a = input()
li = input().split()
print(li.count(a))
print(li)
print(a)
N, i, j = map(int, input().split())
i, j = i - 1, j - 1
line = []
row = []
for a in range(N):
temp = list(map(int, input().split()))
line.append(temp[j])
if a == i:
row = temp
if max(line) == max(row) == row[j]:
print('HAPPY')
else:
print('ANGRY')
BJ_14909 양수 개수 세기 (Bronze III)
numbers = list(map(int, input().split()))
count = 0
for number in numbers:
if number > 0:
count += 1
print(count)
BJ_10871 X 보다 작은 수 (Bronze III)
_, x = map(int, input().split())
for n in map(int, input().split()):
if n < x:
print(n, end=' ')
n_test = int(input())
for _ in range(n_test):
n = int(input())
li = []
for i in range(1, (n + 1) // 2):
li.append(f"{i} {n - i}")
print(f"Pairs for {n}: {', '.join(li)}")
a, b = map(int, input().split())
c, d = map(int, input().split())
f = [a / c + b / d, c / d + a / b, d / b + c / a, b / a + d / c]
print(f.index(max(f)))
T = int(input())
for t in range(T):
n = int(input())
a = 0
for i in range(n):
b = input().rstrip()
if b in ('P R','R S','S P'):
a += 1
elif b in ('R P','S R','P S'):
a -= 1
if a < 0 :
print("Player 2")
elif a > 0:
print("Player 1")
else:
print("TIE")
input()
nums = input().split()
print(nums.count(input()))
month, d, y, hm = input().split()
month = ['January', 'February', 'March', 'April', 'May', 'June', 'July', 'August', 'September', 'October', 'November', 'December'].index(month)
d = int(d[:-1])
y = int(y)
h, m = map(int, hm.split(':'))
db = [31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31]
if y % 400 == 0 or (y % 4 == 0 and y % 100 != 0):
db[1] = 29
total = sum(db) * 24 * 60
cur = (sum(db[:month]) + (d - 1)) * 24 * 60 + h * 60 + m
print(cur / total * 100)
N = int(input())
G = [[0] * 1001 for _ in range(1001)]
for i in range(1, N + 1):
a, b, c, d = map(int, input().split())
for r in range(a, a + c):
for c in range(b, b + d):
G[r][c] = i
for i in range(1, N + 1):
print(sum(li.count(i) for li in G))
import sys
M = int(sys.stdin.readline())
my_list = [False] * 20 # 0 ~ 19
for _ in range(M):
c = sys.stdin.readline().split()
if len(c) > 1:
n = int(c[1]) - 1 # 1 ~ 20 -> 0 ~ 19
if c[0] == 'add':
my_list[n] = True
elif c[0] == 'remove':
my_list[n] = False
elif c[0] == 'check':
print(1 if my_list[n] else 0)
elif c[0] == 'toggle':
my_list[n] = not my_list[n]
elif c[0] == 'all':
my_list = [True] * 20
elif c[0] == 'empty':
my_list = [False] * 20
number_list = []
for i in range(1, 46):
number_list += [i] * i
A, B = map(int, input().split())
print(sum(number_list[A-1:B]))
for _ in range(int(input())):
typing = input()
left, right = [], []
for ch in typing:
if ch == '<':
if left:
right.append(left.pop())
elif ch == '>':
if right:
left.append(right.pop())
elif ch == '-':
if left:
left.pop()
else:
left.append(ch)
left.extend(reversed(right))
print(''.join(left))
print(li[-1][-1])
print(li[1][1])
print(li[1:2][0])
print(li[1:3][1])
print(li[-1][3:])
print(li[-3][-1])
print(li[2][1])
print(li[0][-3])
print(li[-4][3])
print(li[2:][2])
G = []
for _ in range(9):
G.append(list(map(int, input().split())))
mx, mr, mc = 0, 0, 0
for r in range(9):
for c in range(9):
if mx < G[r][c]:
mx = G[r][c]
mr, mc = r + 1, c + 1
print(mx)
print(mr, mc)
N = int(input())400 Bad Request
for _ in range(N):
a, b = input().split()
for ch in b:
print(ch * int(a), end='')
print()
li = [input() for _ in range(5)]
for i in range(15):
for j in range(5):
if i < len(li[j]):
print(li[j][i], end='')
a = int(input())
G = []
for i in range(a):
G.append(input() + 'X')
G.append('X' * (a + 1))
hor, ver = 0, 0
for i in range(a):
for j in range(a - 1):
if G[i][j] == '.' and G[i][j + 1] == '.' and G[i][j + 2] == 'X':
hor += 1
if G[j][i] == '.' and G[j + 1][i] == '.' and G[j + 2][i] == 'X':
ver += 1
print(hor, ver)
BJ 15923 욱제는 건축왕이야!! (Bronze III)
n=int(input())
L = []
for i in range(n):
l = list(map(int,input().split()))
L.append(l)
S = 0
for i in range(n):
S += abs(L[i][0]-L[i-1][0])
S += abs(L[i][1]-L[i-1][1])
print(S)
r = ''
for _ in range(8):
r += input() + '0'
print(r[::2].count('F'))
# O(1)
costs = list(map(int, input().split()))
li = []
for _ in range(3):
e, l = map(int, input().split())
li.extend([(e, 'e'), (l, 'l')])
ret, cur, last = 0, 0, 0
for time, typ in sorted(li):
if typ == 'e':
ret += (time - last) * costs[cur - 1] * cur
cur += 1
else:
ret += (time - last) * costs[cur - 1] * cur
cur -= 1
last = time
print(ret)
import sys
input = sys.stdin.readline
M = int(input())
my_list = [False] * 20 # 0 ~ 19
for _ in range(M):
c = input().split()
if len(c) > 1:
n = int(c[1]) - 1 # 1 ~ 20 -> 0 ~ 19
if c[0] == 'add':
my_list[n] = True
elif c[0] == 'remove':
my_list[n] = False
elif c[0] == 'check':
print(1 if my_list[n] else 0)
elif c[0] == 'toggle':
my_list[n] = not my_list[n]
elif c[0] == 'all':
my_list = [True] * 20
elif c[0] == 'empty':
my_list = [False] * 20
import sys
N, M = map(int, input().split())
G = [list(sys.stdin.readline().rstrip()) for _ in range(N)]
def block_cnt(r, c):
cntWB, cntBW = 0, 0
for i in range(r, r+8):
for j in range(c, c+8):
if (i - r + j - c) % 2 == 0:
if G[i][j] == 'B': cntWB += 1
else: cntBW += 1
else:
if G[i][j] == 'W': cntWB += 1
else: cntBW += 1
return min(cntWB, cntBW)
min_change = N * M
for i in range(N-7):
for j in range(M-7):
min_change = min(min_change, block_cnt(i, j))
print(min_change)
t=[(*map(int,input().split()),) for k in range(int(input()))]
print(*(sum(x < p and y < q for p, q in t) + 1 for x, y in t))
class Solution:
def pancakeSort(self, A: List[int]) -> List[int]:
res = []
for x in range(len(A), 1, -1):
i = A.index(x)
res.extend([i + 1, x])
A = A[:i:-1] + A[:i]
return res
첫번째 줄 n개의 타석이 주어지고, 다음줄에는 n개 타석에서의 각 정수가 주어진다.
N개의 정수가 주어질 때, 볼넷,스트라이크,1루타, 2루타, 3루타, 홈런은 각 -1,0,1,2,3,4 점수를나타냄
볼넷 -1의 경우 타석으로 고려하지 않음
선수의 장타율을 출력하라(장타율은 모든 타석에서의 점수를 더한 값에 n타석으로 나눈 값)
# Iterable → count
n_hit = int(input())
li = list(map(int, input().split()))
miss = li.count(-1)
print((sum(li) + miss) / (n_hit - miss))
첫 줄에 n이 주어진다.
다음 n줄에 숫자가 주어지는데, 이 때 띄어 넘은 수를 모든 수를 출력하라.
만약 1, 2, 3 과 같이 띄어 넘는 숫자가 없을 시는 good job을 출력하라.
n = int(input())
gap = False
prev = 0
for i in range(n):
a = int(input())
for j in range(prev + 1, a):
print(j)
gap = True
prev = a
if not gap:
print('good job')
첫 줄에는 원 케익의 가로 길이가 주어진다.
케익이 정확히 N등분 되어 N개의 줄에 각 조각의 가로 세로 길이가 주어지는데 이 때 원 케익의 세로 길이를 출력하라.
w = int(input())
n_split = int(input())
total = 0
for _ in range(n_split):
a, b = map(int, input().split())
total += a * b
print(total // w)
n 이 짝수이면 n is even 홀수이면 n is odd 라고 출력하라.
n_test = int(input())
for _ in range(n_test):
n = int(input())
if n % 2 == 0:
print(f"{n} is even")
else:
print(f"{n} is odd")
X, Y, N이 첫줄에 주어진다.
1부터 N까지의 자연수 중 X 의 배수는 Fizz, Y의 배수는 Buzz, X, Y의 동시의 배수는 FizzBuzz,
그 외에는 숫자를 출력하라.
x, y, n_line = map(int, input().split())
for i in range(1, n_line + 1):
if i % x == 0 and i % y == 0:
print("FizzBuzz")
elif i % x == 0:
print("Fizz")
elif i % y == 0:
print("Buzz")
else:
print(i)
A+point 혹은 B+point와 같은 형식으로 점수를 출력 할 때 더 많은 점수를 얻는 사람을 출력하라.
s = input()
A = B = 0
for i in range(1, len(s), 2):
if s[i - 1] == 'A':
A += int(s[i])
else:
B += int(s[i])
if A > B:
print('A')
else:
print('B')
첫줄에 문장이 주어진다.
이 때 문장에서 _의 비율, 소문자의 비율, 대문자의 비율, 나머지 부호의 비율을 각각 출력하라.
st = input()
white = 0
lower = 0
upper = 0
symbol = 0
for ch in st:
if ch == '_':
white += 1
elif ch.islower():
lower += 1
elif ch.isupper():
upper += 1
else:
symbol += 1
total = white + lower + upper + symbol
print(white / total)
print(lower / total)
print(upper / total)
print(symbol / total)
팩토리얼을 구한 뒤 마지막 자릿 수를 구하여라.
n_test = int(input())
for _ in range(n_test):
n = int(input())
ret = 1
for i in range(1, n + 1):
ret *= i
print(ret % 10)
첫줄에 테라스의 최대 인원 L과 x개의 이벤트가 주어진다.
각 x줄의 이벤트에는 ‘enter’/‘leave’ 사람수 가 주어지는데 최대 인원 이상으로는 들어올 수 없다.
이때 사람이 많아 거절 당한 이벤트의 개수를 출력하라. (거절 당할 시 enter 해도 추가가 되지 않음)
max_n, n_line = map(int, input().split())
cur, ret = 0, 0
for _ in range(n_line):
st, n = input().split()
n = int(n)
if st == 'enter':
if n + cur <= max_n:
cur += n
else:
ret += 1
else:
cur -= n
print(ret)
첫줄에는 N이, 그 다음 줄에는 N개의 숫자가 주어진다.
N개의 수 중 0보다 작은 수를 출력하라.
N = int(input())
count = 0
for n in map(int, input().split()):
if n < 0:
count += 1
print(count)
첫 줄에 사람 수 N이 주어진다.
1은 항상 줄 앞에 선다.
둘째 줄에 2 .. N과 1과의 거리가 주어진다.
이때 원래 줄을 순서를 출력하라.
n = int(input())
ret = [1] * n
li = list(map(int, input().split()))
for i, n in enumerate(li):
ret[n + 1] = i + 2
print(*ret)
Knuth-Morris-Pratt → KMP
Mirko-Slavko → MS
위와 같이 첫 글자와 - 다음에 나오는 단어를 축약시킬 수 있다. 왼쪽과 같은 인풋이 주어졌을 때 오른쪽과 같이 출력하라.
st = input()
for i, ch in enumerate(st):
if i == 0 or st[i - 1] == '-':
print(st[i], end='')
첫 줄에는 N이 다음 N줄에는 a, b, c가 주어진다.
a는
n_test = int(input())
for _ in range(n_test):
a, b, c = map(int, input().split())
if a > b - c:
print("do not advertise")
elif a == b - c:
print("does not matter")
else:
print("advertise")
C 1m2 에 소모되는 씨앗의 가격
L 라인 의 수
w1 l1 밭의 넓이 높이
…
wL lL
이 때 총 씨앗의 가격을 구하라
c = float(input())
l = int(input())
ret = 0
for _ in range(l):
w, l = map(float, input().split())
ret += w * l * c
print(ret)
첫 줄에는 데이터 한도(한 달에 사용 가능 한 데이터), 두번째 줄에는 N이 주어진다.
각 N줄에는 각 달에 사용한 데이터 량이 주어지는데, 이 때 한도보다 적게 쓸 시 다음달로 이월된다.
이때 N + 1번째 달에 사용할 수 있는 데이터 양을 출력하라.
add = int(input())
n_line = int(input())
cur = 0
for n in range(n_line):
cur += add
cur = max(0, cur - int(input()))
print(cur + add)
첫 줄에 N이 다음 N줄에는 x가 주어진다.
이 때 x의 마지막 자리는 지수이다. (Ex. 35 = 35)
x의 합을 구하라.
n_line = int(input())
ret = 0
for _ in range(n_line):
n = int(input())
ret += (n // 10) ** (n % 10)
print(ret)
a, b, c가 주어 질 때, a, b와 +, -, *, / 로 c를 만들 수 있으면 Possible 불가능 하면 Impossible을 출력하라
n_test = int(input())
for _ in range(n_test):
a, b, c = map(int, input().split())
if a + b == c or a - b == c or b - a == c or a * b == c or a / b == c or b / a == c:
print("Possible")
else:
print("Impossible")
N개의 숫자가 주어질 때 최소인 index를 출력하라
N = int(input())
mn, mn_idx = float('inf'), -1
for i, e in enumerate(map(int, input().split())):
if e < mn:
mn_idx = i
mn = e
print(mn_idx)
5개 줄에 차량 문자가 주어진다.
이 문자에 'FBI'가 포함 되어 있는 라인 숫자를 출력하라.
하나도 없을 시 'HE GOT AWAY'를 출력하라.
seen = False
for i in range(1, 6):
st = input()
if 'FBI' in st:
print(i, end=' ')
seen = True
if not seen:
print("HE GOT AWAY!")
문자를 받아서, 연속된 문자는 한번만 출력하라.
st = input()
for i in range(len(st)):
if i == 0 or st[i - 1] != st[i]:
print(st[i], end='')
루카는 화학 수업 시간에 지루해서 문단에 있는 모음(a,e,i,o,u) 을 모음p모음 으로 바꾸었다.
이 바뀐 문장을 원래대로 돌려라.
st = input()
skip = 0
for ch in st:
if skip > 0:
skip -=1
elif ch in 'aeiou':
skip = 2
print(ch, end='')
else:
print(ch, end='')
첫 줄에 n이 주어진다.
그 다음 n 줄에 k, m이 주어지는데, 이 때 k 와 첫 m개의 자연수, 홀수, 짝수 의 합을 구하라.
n = int(input())
for i in range(n):
k, n = map(int, input().split())
print(k, n * (n + 1) // 2, n * (n + 1) - n, n * (n + 1))
n, m = map(int, input().split())
G = [[0, 0] for i in range(m)]
for i in range(n):
a, b, c = map(int, input().split())
G[a - 1][0] += b
G[a - 1][1] += c
total_wa = 0
total_wb = 0
for a, b in G:
if a < b:
wa = a
wb = b - (a + b) // 2 - 1
print('B', wa, wb)
else:
wa = a - (a + b) // 2 - 1
wb = b
print('A', wa, wb)
total_wa += wa
total_wb += wb
print(abs(total_wa - total_wb) / sum(sum(l) for l in G))
n = int(input())
for _ in range(n):
s = input()
G = []
m = int(len(s) ** 0.5)
for i in range(m):
G.append(s[i * m : (i + 1) * m])
for j in reversed(range(m)):
for i in range(m):
print(G[i][j], end='')
print()
N, M, a, b = map(int, input().split())
G = [input() for _ in range(N)]
for i in range(N):
for _ in range(a):
for j in range(M):
for _ in range(b):
print(G[i][j], end='')
print()
n, m = map(int, input().split())
G = []
for _ in range(n):
G.append(input() + "#")
G.append('#' * (m + 1))
words = []
for i in range(n + 1):
word = ""
for j in range(m + 1):
if G[i][j] == '#':
if len(word) > 1:
words.append(word)
word = ""
else:
word += G[i][j]
for j in range(m + 1):
word = ""
for i in range(n + 1):
if G[i][j] == '#':
if len(word) > 1:
words.append(word)
word = ""
else:
word += G[i][j]
print(sorted(words)[0])
count(‘a’) # count number of str
index(sub[, start[, end]]) # equivalent to find raise value error
isdigit() # Checks if string only contains 0-9
isupper() # Return True if upper case
islower() # Return True if lower case
join(seq) # default empty "".join([str(x) for x in l])
replace(“P”, “-”) # replace P to -
find(sub[, start[, end]]) # lowest index in the string where substring sub is found | -1 if not
rfind(str, beg=0 end=len(string)) # highest index in the string where substring sub is found | -1 if not
rjust(width[, fillchar]) # right justified in a string of specified length
rstrip([chs]) # default whitespaces | e.x. 'mississippi'.rstrip('ipz') → 'mississ'
split(sep=None, maxsplit=-1) # using sep as the delimiter string
startswith(str, beg=0,end=len(self)) # check if starts with str
strip() # removes chars from side (default whitespace)
swapcase() # all the upper case letters are lower case and vice versa
title() # Upper only first char
a = "abcdefaa"
b = "bcd"
print(a.count(a))
print(a.count('a'))
print(a.count('abc'))
print(a.count(b))
print(b.count(a))
print(b.replace('b', 'llll'))
print((a + b).replace('b', 'llll'))
print(b.replace(a, b))
print(a.replace(b, a))
print(a.replace(b, b + b))
a = "abcdefaa"
b = "bcd"
print(a.find(a))
print(a.find('a'))
print(a.find('aa'))
print(a.find(b))
print(b.find(a))
print(b in a)
print(b in b)
print(b + b in a)
print((b in b) == (a in a))
print((a in a) == (b in b))
count = 0
for i in range(1, 6):
if input().find('FBI') != -1:
print(i, end=' ')
count +=1
if count == 0:
print("HE GOT AWAY!")
BJ_4458 첫 글자를 대문자로 (Bronze II)
for i in range(int(input())):
j = input()
print(j[0].upper() + j[1:])
a = int(input())
b = int(input())
c = int(input())
s = str(a * b * c)
for i in range(10):
print(s.count(str(i)))
a = input()
print(a.count('a') + a.count('e') + a.count('i') + a.count('o') + a.count('u'))
a, b = input().split()
mx = int(a.replace('5', '6')) + int(b.replace('5', '6'))
mn = int(a.replace('6', '5')) + int(b.replace('6', '5'))
print(mn, mx)
s = input()
for i in range(ord('a'), ord('z') + 1):
print(s.find(chr(i)), end=' ')
st = input()
for ch in st:
if ch.islower():
print(ch.upper(), end='')
else:
print(ch.lower(), end='')
BJ_2902 KMP는 왜 KMP일까 (Bronze II)
for i in input():
if i.isupper():
print(i, end='')
input()
s = input()
if 'L' not in s:
print(len(s))
else:
print(len(s.replace("LL", "S")) + 1)
a=input().replace('XXXX','AAAA').replace('XX','BB')
print(-1 if 'X' in a else a)
s = input()
k = input()
print(int(k in s))
첫번째 줄에는 N이 그 다음 N 줄에는 x가 주어진다. 이때 각 줄마다 x의 자리수를 출력하라.
n_line = int(input())
for _ in range(n_line):
x = input()
print(len(x))
첫줄에 N이 주어진다.
다음 각각 N줄에 문자가 주어지는데, 이 때 CD를 포함하지 않는 줄의 수를 구하여라.
n = int(input())
ret = 0
for _ in range(n):
if input().find('CD') == -1:
ret += 1
print(ret)
input에 ss, 즉 연속된 s가 있을 시 'hiss' 그렇지 않으면 'no hiss'를 출력한다.
# Using for
s = input()
for i in range(1, len(s)):
if s[i] == s[i - 1] == 's':
print("hiss")
break
else:
print("no hiss")
# Using find
s = input()
if s.find('ss') == -1:
print('no hiss')
else:
print('hiss')
첫줄엔 N 이 그 다음 N 줄엔 문자가 주어진다.
이 때 rose나 pink를 포함한 문자의 수를 구하라. (단 대문자 / 소문자는 무시한다.)
N = int(input())
count = 0
for _ in range(N):
st = input().lower()
if st.find('pink') != -1 or st.find('rose') != -1:
count += 1
print(count if count != 0 else "I must watch Star Wars with my daughter")
두줄에 거쳐 총 8개의 수가 주어진다.
이 때 위 줄의 합이 크면 Emma 아랫줄의 합이 크면 Gunnar, 같을 시에는 Tie를 출력하라.
a = sum(map(int, input().split()))
b = sum(map(int, input().split()))
if a < b:
print('Emma')
elif b < a:
print('Gunnar')
else:
print('Tie')
예제 참조
t, s = input().split()
if t == 'E':
row = 1
for i, ch in enumerate(s):
if i == len(s) - 1 or s[i + 1] != s[i]:
print(ch + str(row), end='')
row = 1
else:
row+=1
else:
for i in range(1, len(s), 2):
print(s[i - 1] * int(s[i]), end='')
문자 Y, P가 주어진다.
1. Y가 ex로 끝날 시 Y + P
2. Y가 e로 끝날 시 Y + 'e' + P
3. Y가 aiou 로 끝날 시 그 모음을 제거하고 Y + 'ex' + P
4. 위에 어느 것도 아닐 시 Y + 'ex' + P
를 출력한다
a, b = input().split()
if a[-1] == 'e':
print(a, 'x', b, sep='')
elif a[-2:] == 'ex':
print(a, b, sep='')
elif a[-1] in 'aiou':
print(a[:-1], 'ex', b, sep='')
else:
print(a, 'ex', b, sep='')
문장에 ae가 포함 된 단어가 40% 이상이면 스웨덴 어이다.
첫 줄에 문장이 주어질 때 스웨덴 어이면 dae ae ju traeligt va 아니면 haer talar vi rikssvenska 을 출력하라.
li = input().split()
n = len(li) * 0.4
count = 0
for st in li:
if "ae" in st:
count += 1
if n <= count:
print("dae ae ju traeligt va")
else:
print("haer talar vi rikssvenska")
i = 1
n = 10
while i < 5: print(i, end = ' '); i += 1
while i < 5: print(i * 5, end = ' '); i += 1
while i < 5: print(i, end = ' '); i *= 2
while n > 0: print(n, end = ' '); n//=2
while n != 0: print(n, end = ' '); n-= 2
while n % 2 == 0 and n > 0: print(n, end = ' '); n -= 1
while n > 0 and i < 10: print(i*n, end = ' '); i += 2; n -= 2
while n > i: print(n, end = ' '); n -= 1; i += 1
while i != n: print(i); i -= 1
while n > i: print(n, end = ' '); n -= i
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break
print(a//b, a % b, '/', b)
n, T = map(int, input().split())
times = list(map(int, input().split()))
count = 0
for time in times:
T -= time
if T < 0:
break
count += 1
print(count)
while True:
a, b, c = map(int, input().split())
if a == b == c == 0:
break
if c - b == b - a:
print(f"AP {c + (b - a)}")
else:
print(f"GP {c * (b // a)}")
while True:
A, B, C = map(int, input().split())
if A == B == C == 0:
break
if max(A, B, C) >= A + B + C - max(A, B, C):
print("Invalid")
elif A == B == C:
print("Equilateral")
elif A == B or B == C or A == C:
print("Isosceles")
else:
print("Scalene")
while True:
a, b = map(int, input().split())
if a == 0 and b == 0:
break
if b % a == 0:
print('factor')
elif a % b == 0:
print('multiple')
else:
print('neither')
last = float(input())
while True:
n = float(input())
if n == 999:
break
print(f"{n - last:.2f}")
last = n
BJ_10952 A + B - 5 (Bronze III)
while True:
a, b = map(int, input().split())
if a == b == 0:
break
else:
print(a + b)
while True:
a, b = map(int, input().split())
if a == b == 0:
break
if a > b:
print("Yes")
else:
print("No")
while True:
a, b, c = sorted(map(int, input().split()))
if a == 0:
break
if c ** 2 == a ** 2 + b ** 2:
print("right")
else:
print('wrong')
a, b = map(int, input().split())
for n in range(2, b):
if a % n == 0:
print("BAD", n)
break
else:
print("GOOD")
a = int(input())
while True:
b = int(input())
if b == 0:
break
if b % a == 0:
print(b, f"is a multiple of {a}.")
else:
print(b, f"is NOT a multiple of {a}.")
cn = int(input())
count = 1
while cn != 1:
count += 1
if cn % 2 == 0:
cn = cn // 2
else:
cn = 3 *cn + 1
print(count)
BJ_5612 터널의 입구와 출구 (Bronze III)
n = int(input())
m = res = int(input())
for _ in range(n):
a,b = map(int, input().split())
m += a - b
res = max(m,res)
if m < 0:
print(0)
break
else:
print(res)
N = int(input())
print_num = 0
for i in range(N+1):
sum_num = i + sum(map(int, str(i)))
if(sum_num == N):
print(i)
break
else:
print(0)
n = int(input())
m = n
i = 0
while True:
m = m % 10 * 10 + (m % 10 + m // 10) % 10
i += 1
if m == n:
print(i)
Break
def solution(a):
ret, cur = 1, 1
while cur < a:
cur += 6 * ret
ret += 1
return ret
print(solution(int(input())))
ret = 0
for coin in [500, 100, 50, 10, 5, 1]:
while (coin <= n):
n -= coin
ret+=1
print(ret)
n=int(input())
A=0
B=1
while n>A:
A+=B
B+=1
if B%2==0:
print(f'{1+A-n}/{B-(1+A-n)})
else:
print(f'B-(1+A-n)/1+A-n')
n_test = int(input())
for _ in range(n_test):
n = int(input())
mx = 1
while n != 1:
mx = max(mx, n)
if n % 2 == 0:
n //= 2
else:
n = n * 3 + 1
print(mx)
def is_palin(st):
for i in range(len(st)):
if st[i] != st[len(st) - i - 1]:
return False
return True
while True:
n = input()
if n == '0':
break
if is_palin(n):
print("yes")
else:
print("no")
n = 1000- int(input())
li = [True] * 10090
def d(n):
ret = n
while n:
ret += n % 10
n //= 10
return ret
for n in range(10000):
li[d(n)] = False
for i in range(10001):
if li[i]:
print(i)
n = int(input())
n,k=map(int,input().split(' '))
index=k-1
a=list(range(1,n+1))
r=[]
while a:
index%=len(a)
r.append(str(a.pop(index)))
index+=k-1
print("<"+", ".join(r)+">")
name = 666
cnt=0
while(True):
if "666" in str(name):
cnt+=1
if cnt == n :
print(name)
break
name+=1
doc = input()
word = input()
count = 0
i = 0
while i <= len(doc) - len(word):
if doc[i:i + len(word)] == word:
count += 1
i += len(word)
else:
i += 1
print(count)
mn = int(input())
mx = int(input())
sm = int(input())
def match(n, sm):
while n != 0:
sm -= n % 10
n //= 10
return sm == 0
for i in range(mn, mx + 1):
if match(i, sm):
print(i)
break
for i in range(mx, mn - 1, -1):
if match(i, sm):
print(i)
break
숫자 a, 문자 b가 매 줄마다 주어진다.
이 때 문자를 뒤집어서 a만큼 회전한 문자를 출력한다. (단 Z → _ → . → A 으로 순환된다)
마지막 줄에는 0만 나온다.
alp = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ_.'
while True:
raw = input()
if raw == '0':
break
shift, st = raw.split()
shift = int(shift)
for ch in reversed(st):
print(alp[(alp.find(ch) + shift) % len(alp)], end='')
print()
첫 줄에 a, b가 주어진다. 이 때 a는 총 방의 개수이다. (1...n)
다음 b 줄에 예약된 방 번호가 주어진다.
이때 아무 빈 방을 출력하라.
빈 방이 없을 시 too late을 출력하라.
a, b = map(int, input().split())
se = set()
for _ in range(b):
se.add(int(input()))
for i in range(1, a + 1):
if i not in se:
print(i)
break
else:
print("too late")
각 줄에 a, b 가 주어진다.
이 때 a / b 인 분수를 대분수로 형식으로 출력하라.
a, b가 둘다 0 일 경우 종료한다.
while True:
dem, num = map(int, input().split())
if dem == num == 0:
break
print(dem // num, dem % num, '/', num)
첫 줄에 e, f, c 가 주어진다.
e와 f 를 합치면 가지고 있는 총 빈 병의 개수가 나오고,
병을 c개 가지고 오면 꽉 찬 음료수를 받을 수 있다.
이 때 총 마실 수 있는 음료수의 수를 출력하라.
e, f, c = map(int, input().split())
e += f
ret = 0
while e >= c:
ret += e // c
e = e % c + e // c
print(ret)
x1, x2, y1, y2이 주어진다.
이때 를 출력하라.
마지막 줄에 0이 나온다.
while True:
raw = input()
if raw == '0':
break
a, b, c, d, e = map(float, raw.split())
print((abs(a - c) ** e + abs(b - d) ** e) ** (1/e))
harshad 수는 각 자리 수를 다 더한 수로 나누어 떨어지는 수이다.
n이 주어질 때 n보다 크거나 같은 가장 작은 harshad 수를 출력하라.
def is_harshad(num):
digit_sum = 0
cur = num
while cur != 0:
digit_sum += cur % 10
cur //= 10
return num % digit_sum == 0
n = int(input())
while True:
if is_harshad(n):
print(n)
break
n = n + 1
N-test개의 줄에 k(data set 수),b,n 정수가 주어진다
k개의 줄에 각 test 번호 k와 SSB(b,n)을 출력하라
n_test = int(input())
def SSD(b, n):
ret = 0
while n != 0:
ret += (n % b) ** 2
n //= b
return ret
for _ in range(1, n_test + 1):
K, b, n = map(int, input().split())
print(f'{K} {SSD(b, n)}')
def SOD(st):
return sum(map(int, st))
while True:
n = input()
if n == '0':
break
for i in range(11, 100000):
if SOD(n) == SOD(str(int(n) * i)):
print(i)
break
si = 0
while True:
si += 1
n = int(input())
if n == 0:
break
print(f"SET {si}")
li = [input() for _ in range(n)]
for i in range(0, n, 2):
print(li[i])
for i in range(1, n, 2):
print(li[i])
N, M이 주어지고 N개의 라인의 주차장이 주어진다.
이 때 . 은 빈칸, '#' 은 건물, 'X' 는 다른 차량이다.
2x2의 차를 주차 할 때 0, 1, 2, 3, 4개의 차량을 치우고 댈 수 있는 가지 수를 각 라인에 출력하라.
N, M = map(int, input().split())
G = []
for _ in range(N):
G.append(input())
rets = [0, 0, 0, 0, 0]
for i in range(1, N):
for j in range(1, M):
spaces = [G[i - 1][j - 1], G[i - 1][j], G[i][j - 1], G[i][j]]
if '#' in spaces:
continue
rets[spaces.count('X')] += 1
for ret in rets:
print(ret)
a = set(['a', 'b', 'b'])
b = set(['b', 'c', 'd'])
print('d' in a)
print('d' in a | b)
print(" ".join(sorted(a)))
print(" ".join(sorted(a & b)))
a.remove('a'); print(" ".join(a))
print(" ".join(sorted(a | b)))
print(" ".join(sorted(a | {'z'})))
a.add('f'); print(" ".join(a))
print(" ".join(sorted(a - b)))
print(" ".join({'1', '1'}))
n = int(input())
st = (input())
has = 0
for i, ch in enumerate(st):
has = (has + 31 ** i * (ord(ch) - ord('a') + 1)) % 1234567891
print(has)
st = set()
for i in range(10):
st.add(int(input()) % 42)
print(len(st))
input()
li = list(map(int, input().split()))
print(len(li) - len(set(li)))
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
names = []
name2i = {}
for i in range(n):
name = input().strip()
names.append(name)
name2i[name] = i
for _ in range(m):
i = input().strip()
if i.isdigit():
print(names[int(i) - 1])
else:
print(name2i[i] + 1)
N, M = map(int, input().split())
A = set(map(int, input().split()))
B = set(map(int, input().split()))
li = list(sorted(A - B))
print(len(li))
print(*li)
input()
se = set(map(int, input().split()))
input()
for n in map(int, input().split()):
print(1 if n in se else 0)
n, m = map(int, input().split())
hear = set(input() for _ in range(n))
watch = set(input() for _ in range(m))
print(len(hear & watch))
print("\n".join(sorted(hear & watch)))
첫 줄에는 N, 다음 N 줄엔 대학이름 팀이름이 순위대로 주어진다.
상을 받는 상위 12팀 이름을 출력하라, 단 한 대학에서는 한 팀만 상을 받을 수 있다.
N = int(input())
seen = set()
for _ in range(N):
uni, team = input().split()
if uni not in seen and len(seen) < 12:
print(uni, team)
seen.add(uni)
첫 줄에 테스트 케이스 수.
각 테스트 케이스는 N 과 N개의 줄에 도시이름이 주어진다.
이 때 다른 도시 개수를 출력하라.
n_test = int(input())
for _ in range(n_test):
N = int(input())
se = set()
for _ in range(N):
se.add(input())
print(len(se))
10개의 수가 주어지는데 이 때 42의 나머지의 가짓수를 구하라.
st = set()
for i in range(10):
st.add(int(input()) % 42)
print(len(st))
첫줄에 N이 주어지고 그 다음 N줄에 방명록이 주어진다.
방명록은 입장 이름 / 퇴장 이름과 같은 형식으로 주어지는데,
이 때 퇴장 전 입장을 여러번 했거나 입장 하지 않았는데 퇴장 한 경우는 (ANOMALY)를 출력한다.
N = int(input())
se = set()
for _ in range(N):
typ, name = input().split()
if typ == 'entry':
if name in se:
print(name, 'entered', '(ANOMALY)')
else:
print(name, 'entered')
se.add(name)
else:
if name in se:
print(name, 'exited')
se.remove(name)
else:
print(name, 'exited', ('(ANOMALY)' if name not in se else ''))
print(d1['a'])
print(d2['c'])
print(d1['a'] + d2['c'])
print(d1['c'] + d2['a'])
print('a' in d1)
print('d' in d2)
print(d2['b']*d1['b'])
print(d1 + d2)
print(d2['d'])
print(list(d2.values()))
from collections import Counter
a = Counter([1, 2, 3, 4, 5, 5])
b = Counter([-1, 2, 3, 4, 4, 5])
print(a[3])
print(b[4])
print(a[-2])
print(b[-1])
print((a + b)[4])
print((a + b)[-1])
print((a-b)[5])
print((b-a)[5])
print((a+a)[4])
print((b+b)[4])
GPA = {'A+': 4.3, 'A0': 4.0, 'A-': 3.7, 'B+': 3.3, 'B0': 3.0, 'B-': 2.7, 'C+': 2.3, 'C0': 2.0, 'C-': 1.7,
'D+': 1.3, 'D0': 1.0, 'D-': 0.7, 'F': 0.0}
print(GPA[str(input())])
N, Q = map(int, input().split())
site2pw = {}
for _ in range(N):
site, pw = input().split()
site2pw[site] = pw
for _ in range(Q):
print(site2pw[input()])
while True:
n = int(input())
if n == 0:
break
l1 = [int(input()) for _ in range(n)]
l2 = list(sorted([int(input()) for _ in range(n)]))
rank = {}
for i, e in enumerate(sorted(l1)):
rank[e] = i
for e in l1:
print(l2[rank[e]])
print()
import collections
input()
co = collections.Counter(input())
if co['A'] < co['B']:
print('B')
elif co['B'] < co['A']:
print('A')
else:
print("Tie")
from collections import Counter
N = int(input())
x_cnt = Counter()
y_cnt = Counter()
for _ in range(N):
x, y = map(int, input().split())
x_cnt[x] += 1
y_cnt[y] += 1
ret = 0
for x in x_cnt:
if x_cnt[x] > 1:
ret += 1
for y in y_cnt:
if y_cnt[y] > 1:
ret += 1
print(ret)
import string
from collections import Counter
cnt1 = Counter(input())
cnt2 = Counter(input())
ret = 0
for ch in string.ascii_lowercase:
ret += abs(cnt1[ch] - cnt2[ch])
print(ret)
from collections import Counter
import sys
input = sys.stdin.read
co = Counter(input().replace(' ', '').replace('\n', ''))
for k in sorted(co.keys()):
if co[k] == max(co.values()):
print(k, end='')
from collections import Counter
N = int(input())
G = []
c1 = Counter()
c2 = Counter()
c3 = Counter()
for _ in range(N):
a, b, c = map(int, input().split())
c1[a] += 1
c2[b] += 1
c3[c] += 1
G.append([a, b, c])
for a, b, c in G:
print((a if c1[a] == 1 else 0) + (b if c2[b] == 1 else 0) + (c if c3[c] == 1 else 0))
import collections
st = input()
cnter = collections.Counter(st.lower())
mc = cnter.most_common(2)
if len(mc) == 2 and mc[0][1] == mc[1][1]:
print('?')
else:
print(mc[0][0].upper())
def is_group(st):
dic = {}
for i, ch in enumerate(st):
if ch in dic and dic[ch] != i - 1:
return False
dic[ch] = i
return True
n_test = int(input())
ret = 0
for _ in range(n_test):
if is_group(input()):
ret += 1
print(ret
BJ_1620 나는야 포켓몬 마스터 (Silver IV)
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
names = []
name2i = {}
for i in range(n):
name = input().strip()
names.append(name)
name2i[name] = i
for _ in range(m):
i = input().strip()
if i.isdigit():
print(names[int(i) - 1])
else:
print(name2i[i] + 1)
import sys
from collections import Counter
n_test = int(input())
dic = Counter()
top, ret = 0, 0
for _ in range(n_test):
n = int(sys.stdin.readline())
dic[n]+=1
if dic[n] > top or dic[n] == top and n < ret:
top, ret = dic[n], n
print(ret)
import collections
input()
cnt = collections.Counter(map(int, input().split()))
input()
for n in map(int, input().split()):
print(cnt[n])
from collections import Counter
def is_sim(a, b):
c1 = Counter(a)
c2 = Counter(b)
return max(sum((c1 - c2).values()), sum((c2 - c1).values())) <= 1
n = int(input())
li = [input() for _ in range(n)]
ret = 0
for i in range(1, n):
if is_sim(li[0], li[i]):
ret += 1
print(ret)
W와 B의 개수가 같으면 1 아니면 0을 출력하라.
from collections import Counter
cnt = Counter(input())
print(1 if cnt['W'] == cnt['B'] else 0)
첫 줄의 N과 B이 주어진다.
그 다음 N줄에 Value, Suit 이 주어지는데,
Suit 이 B와 같을 시 Dominant, 다를 시 Not dominant 점수를 얻는다. 총 합을 출력하라.
n_line, suit = input().split()
n_line = int(n_line)
dic = {'A': (11, 11), 'K': (4, 4), 'Q': (3, 3), 'J':(20, 2), 'T': (10, 10), '9': (14, 0), '8' : (0, 0), '7': (0, 0)}
ret = 0
for _ in range(n_line * 4):
card = input()
if card[1] == suit:
ret += dic[card[0]][0]
else:
ret += dic[card[0]][1]
print(ret)
5개의 포커카드가 주어진다.
첫번째 문자가 카드의 랭크인데 이때 가장 많이 등장하는 랭크의 개수를 출력하라
from collections import Counter
cnter = Counter()
for card in input().split():
cnter[card[0]]+=1
print(cnter.most_common(1)[0][1])
5명의 사람이 요리 대결을 한다.
최고점을 받은 사람의 줄 수와 총점을 출력하라
from collections import Counter
cnter = Counter()
for i in range(5):
cnter[i + 1] = sum(map(int, input().split()))
print(*cnter.most_common(1)[0])
문자열이 주어진다.
이 때 T, C, G 중 가장 적게 나온 개수 * 7 + T 개수^2 + C 개수^2 + G 개수^2 의 합을 구하라
from collections import Counter
st = input()
co = Counter(st)
ret = min(co['T'], co['C'], co['G']) * 7
ret += co['T'] ** 2
ret += co['C'] ** 2
ret += co['G'] ** 2
print(ret)
Peragrams은 문자를 뒤섞었을 때 Palindrome이 되는 문자다.
첫 줄에 문자열이 주어 졌을 때 최소 문자 몇개를 제거해야 Peragrams이 되는지 출력하라.
from collections import Counter
cnt = Counter()
for ch in input():
cnt[ch] += 1
ret = 0
for count in cnt:
if cnt[count] % 2 == 1:
ret += 1
print(max(0, ret - 1))
한 테스트 마다
첫 줄에 띄어쓰기로 나누어진 울음 소리
두번째 줄부터는 animal says ~
마지막 줄에는 what does the fox say? 가 나온다.
이때 다른 동물이 내지 않은 울음소리를 모두 출력하라.
n_test = int(input())
for _ in range(n_test):
li = input().split()
s = input()
ignore = set()
while s != 'what does the fox say?':
ignore.add(s.split()[-1])
s = input()
for e in li:
if e not in ignore:
print(e, end=' ')
문제를 풀 때 정답이면 정답인 시간을 더하고,
오답이면 그 문제에 대한 penalty가 20분 씩 쌓여 그 문제를 맞았을 때 기존에 쌓인 페널티를 합쳐서 시간을 계산한다.
시간, 문제, 결과가 입력 될 때 총 시간을 구하라
-1 이 입력될 까지 계속 된다.
from collections import Counter
total_score = total_time = 0
penalty = Counter()
while True:
st = input()
if st == '-1':
break
t, prob, result = st.split()
t = int(t)
if result == 'wrong':
penalty[prob] += 20
elif result == 'right':
total_time += t + penalty[prob]
total_score += 1
print(total_score, total_time)
9개의 숫자가 주어진다. 그 중 7개의 숫자의 합은 100이다. 그 7개의 숫자를 출력하라.
from itertools import combinations
li = []
for _ in range(9):
li.append(int(input()))
for p in combinations(li, 7):
if sum(p) == 100:
print(*p, sep='\n')
break
직선으로 되어있는 시장에서 모든 n개의 가게에서 장을 본다.
이때 총 이동거리를 최소화 시키는 시작점에서 모든 장을 보고 돌아오는 데까지 걸리는 거리를 출력하라.
n_test = int(input())
for i in range(n_test):
N = int(input())
li = list(map(int, input().split()))
print((max(li) - min(li)) * 2)
첫 줄에는 n이, 그 다음 n 번째 줄에는 a, b가 주어진다.
n개의 a * b 의 합을 구하라.
n_line = int(input())
ret = 0
for _ in range(n_line):
a, b = map(float, input().split())
ret += a * b
print(ret)
n개 줄의 a + b가 주어진다. 이 때 결과 값을 출력하라. 단 P=NP 가 주어질 때는 skipped를 출력하라.
n_test = int(input())
for _ in range(n_test):
line = input()
if line == 'P=NP':
print('skipped')
else:
print(eval(line))
a, b, c 가 주어질 때
사칙연산으로 a ? b = c가 되거나 a = b ? c가 되는 경우중 한가지를 출력하라
a, b, c = input().split()
for op in ['+', '-', '*', '/']:
if eval(a + op + b) == int(c):
print(a + op + b + '=' + c)
break
if int(a) == eval(b + op + c):
print(a + '=' + b + op + c)
break
N개의 문장에 영어 알파벳 a-z까지 없는 알파벳을 출력하라. 모두 있을 시 pangram을 출력하라.
N = int(input())
for _ in range(N):
sentence = input().lower()
missings = []
for ch in 'abcdefghijklmnopqrstuvwxyz':
if ch not in sentence:
missings.append(ch)
if len(missings) == 0:
print("pangram")
else:
print("missing " + "".join(missings))
def shortest_pattern(sentence):
n = len(sentence)
for i in range(1, n + 1):
if (sentence[:i] * (n // i + 1))[:n] == sentence:
return i
return n
N = int(input())
for i in range(N):
sent = input()
print(shortest_pattern(sent))
LC_347 top-k-frequent-elements
def topKFrequent(self, nums: List[int], k: int) -> List[int]:
co = collections.Counter(nums)
return [a for a, b in co.most_common(k)]
print(' '.join(['1', '2', '3']))
print(' '.join(['1']))
print('+'.join(['1', '2', '3']))
print('+'.join(['1']))
print('+'.join("ABC"))
print('-'.join(reversed(['a', '', 'a'])))
print('-'.join(reversed(['', '', 'a'])))
print('-'.join(reversed([1, 2, 3])))
print('-'.join(reversed('abcd')))
print('-'.join(reversed(['1', '2', '3'])))
a, b = map(int, input().split())
def rev(a):
return int("".join(reversed(str(a))))
print(rev(rev(a) + rev(b)))
# submit in pypy KOI 2019 1차대회
a = int(input())
li = []
for _ in range(a):
li.append(int(input()))
mx, ret = 0, 0
for n in reversed(li):
if mx < n:
mx = n
ret += 1
print(ret)
n, m = map(int, input().split())
for i in range(n):
print("".join(reversed(input())))
while True:
a = input()
if a == "END":
break
print("".join(reversed(a)))
def count_visible(li):
count, cur_mx = 0, 0
for e in li:
if e > cur_mx:
count += 1
cur_mx = e
return count
li=[int(input()) for _ in range(int(input()))]
print(count_visible(li))
print(count_visible(reversed(li)))
예제 참조
n_test = int(input())
for test in range(1, n_test + 1):
R, C = map(int, input().split())
G = [input() for _ in range(R)]
print(f"Test {test}")
for st in reversed(G):
print("".join(reversed(st)))
a, b, c, d = sorted(map(int, input().split()))
print(abs(d + a - (b + c)))
li = list(map(int, input().split()))
print(*sorted(li))
y1, m1, d1 = map(int, input().split())
y2, m2, d2 = map(int, input().split())
k_age = y2 - y1 + 1
if (m1, d1) > (m2, d2):
age = k_age - 2
else:
age = k_age - 1
print(age)
print(k_age)
print(k_age - 1)
li = [input() for _ in range(4)]
if len(set(li)) == 1:
print("Constant Depth")
elif list(sorted(li)) == li:
print("Fish Rising")
elif list(sorted(li, reverse=True)) == li:
print("Fish Diving")
else:
print("No Fish")
a, b, c, d = sorted(map(int, input().split()))
print(a * c)
a, b, c = sorted(map(int,input().split()))
if b - a == c - b:
print(2 * c - b)
elif b - a < c - b:
print((b + c) // 2)
else:
print((a + b) // 2)
# O(N logN) → Correct
N = int(input())
li = list(sorted(map(int, input().split())))
ret = 0
for i, e in enumerate(li):
ret += (e * (2 * i - len(li) + 1) * 2)
print(ret)
li = [int(input()) for _ in range(5)]
li.sort()
print(sum(li) // 5)
print(li[2])
li = list(sorted(map(int, input().split())))
dic = {'A' : 0, 'B' : 1, 'C' : 2}
order = input()
print(li[dic[order[0]]], li[dic[order[1]]], li[dic[order[2]]])
while True:
a, b, c = sorted(map(int, input().split()))
if a == 0:
break
if c ** 2 == a ** 2 + b ** 2:
print("right")
else:
print('wrong')
li = list(map(int, input().split()))
if li == sorted(li):
print("ascending")
elif li == sorted(li, reverse=True):
print("descending")
else:
print("mixed")
BJ_10867 중복 빼고 정렬하기 (Silver V)
input()
print(*sorted(set(map(int, input().split()))))
input()
li1, li2 = list(map(int, input().split())), list(map(int, input().split()))
print(*sorted(li1 + li2))
import sys
input = sys.stdin.readline
n = int(input())
li = [int(input()) for _ in range(n)]
for e in sorted(li, reverse=True):
print(e)
import sys
l = []
for _ in range(int(sys.stdin.readline())):
l.append(int(sys.stdin.readline()))
print("\n".join(map(str, sorted(l))))
for _ in range(int(input())):
print(sorted(map(int, input().split()))[-3])
k=int(input().split()[1])
print(sorted(map(int,input().split()))[k-1])
a = input()
print("".join(sorted(a, reverse=True)))
a = int(input())
li = []
for _ in range(a):
li.append(int(input()))
li.sort() # same as li = sorted(li)
for n in li:
print(n)
BJ_11650 Sort coordinate (Silver V)
n = int(input())
li = []
for _ in range(n):
a, b = map(int, input().split())
li.append((a, b))
for a, b in sorted(li):
print(a, b)
BJ_11651 Sort coordinate 2 (Silver V)
n = int(input())
li = []
for _ in range(n):
a, b = map(int, input().split())
li.append((b, a))
for a, b in sorted(li):
print(b, a)
n_test = int(input())
se = set()
for _ in range(n_test):
se.add(input())
for w in sorted(se, key=(lambda x: (len(x), x))):
print(w)
import sys
n_test = int(sys.stdin.readline())
li = []
for _ in range(n_test):
age, name = input().split()
li.append((int(age), name))
for age, name in sorted(li, key=(lambda x: x[0])):
print(age, name)
import sys
a = int(input())
dic = {}
for _ in range(a):
n = int(sys.stdin.readline())
if n in dic:
dic[n] += 1
else:
dic[n] = 1
for n in sorted(dic.keys()):
for _ in range(dic[n]):
print(n)
li = []
for _ in range(N):
name, a, b, c = input().split()
li.append(tuple((-int(a), int(b), -int(c), name)))
for e in sorted(li):
print(e[3])
from collections import Counter
n, c = map(int, input().split())
li = input().split()
co = Counter(li)
print(" ".join(sorted(li, key=co.get, reverse=True)))
from collections import Counter
s = input()
co = Counter(s)
odds = [k for k in co if co[k] % 2 != 0]
if 1 < len(odds):
print("I'm Sorry Hansoo")
else:
ret = ""
for k in sorted(co):
ret += k * (co[k] // 2)
print(ret + ("" if len(odds) == 0 else odds[0]) + ret[::-1])
N = int(input())
li = list(map(int, input().split()))
i2comp = {n : i for i, n in enumerate(list(sorted(set(li))))}
print(*[i2comp[i] for i in li])
for _ in range(int(input())):
n = int(input())
li = [input() for _ in range(n)]
li.sort()
for i, j in zip(li, li[1:]):
if i == j[:len(i)]:
print("NO")
break
else:
print("YES")
def firstBadVersion(self, n):
lo, hi = 1, n
while lo < hi:
mi = (lo + hi) // 2
if not isBadVersion(mi):
lo = mi + 1
else:
hi = mi
return lo
숫자 4개가 주어진다. 이때 만들 수 있는 가장 큰 직사각형을 구하여라. (긴 변은 직사각형을 나가도 됨)
a, b, c, d = sorted(map(int, input().split()))
print(a * c)
n개 줄에
색 반지름 / 지름 색
둘 중 하나의 포맷으로 주어진다.
이 색들을 작은 반지름 순서대로 출력하라.
n_line = int(input())
li = []
for _ in range(n_line):
a, b = input().split()
if a.isdigit():
li.append((int(a), b))
else:
li.append((int(b) * 2, a))
for _, color in sorted(li):
print(color)
n_team = int(input())
li = list(sorted([int(input()) for _ in range(n_team)], reverse=True))
score = 0
for i, n in enumerate(li):
score += n * (0.8 ** i)
print(score / 5)
score = 0
for i, n in enumerate(li):
up = i
stay = (n_team - 1 - i)
score += n * (up * (0.8 ** (i - 1)) + stay * (0.8 ** i))
print(score / 5 / n_team)
첫줄에 N 그 다음 N 줄에 사람 이름이 주어진다.
이 때 사람 이름이 알파벳 순서 일시 INCREASING,
알파벳 역순 일시 DECREASING,
둘 다 아니면 NEITHER을 출력하라.
n = int(input())
li = []
for _ in range(n):
li.append(input())
if li == sorted(li):
print("INCREASING")
elif li == sorted(li, reverse=True):
print('DECREASING')
else:
print('NEITHER')
print(''.join(tuple(['1', '2'])))
print(''.join(tuple("abc")))
print((5, 4) < (5, 3))
print(('b', 4) < ('c', 3))
print((1, 2, 3) < (1, 2))
print((1, 2) == (1, 2))
print(sorted([(100, 'tom'), (90, 'sean')])[0][1])
# print(tuple([1, 2]) < tuple(['a', 1]))
for a, b in zip([1, 2], [3, 4]):
print(a, b, end='-')
for a in enumerate([1, 2]):
print(a[0], a[1])
n = int(input())
a, b = 1, 0
for i in range(n):
a, b = b, a + b
print(b)
a_scores = list(map(int,input().split()))
b_scores = list(map(int,input().split()))
a_point = b_point = 0
last = 'D'
for a_score, b_score in zip(a_scores, b_scores):
if a_score > b_score:
last = 'A'
a_point += 3
elif a_score < b_score:
last = 'B'
b_point += 3
else:
a_point += 1
b_point += 1
print(a_point, b_point)
if a_point > b_point:
print("A")
elif b_point < a_point:
print("B")
else:
print(last)
N, _ = map(int, input().split())
G1, G2 = [], []
for _ in range(N):
G1.append(list(map(int, input().split())))
for _ in range(N):
G2.append(list(map(int, input().split())))
for l1, l2 in zip(G1, G2):
for a, b in zip(l1, l2):
print(a + b, end=' ')
print()
n = int(input())
li1 = sorted(map(int, input().split()))
li2 = sorted(map(int, input().split()), reverse=True)
ret = 0
for n1, n2 in zip(li1, li2):
ret += n1 * n2
print(ret)
첫줄에 출발시간s, 수업시작시간t, n이 주어진다. 두번째 줄에는 n+1개의 수가 주어지며 한 정거장에서 다음정거장으로 가는데 걸리는 시간을 의미.
세번째 줄에는 n개의 수가 주어지며 버스타고가면서 걸리는시간을 의미.
네번째 줄에도 n 개의 수가 주어진다.버스가 정거장에 도착하는데 걸리는시간
제시간에 수업에 도착할 수 있으면 ‘yes’ 없으면 ‘no’를 출력하라
cur, t, n = map(int, input().split())
D = list(map(int, input().split()))
B = list(map(int, input().split()))
C = list(map(int, input().split()))
for d, b, c in zip(D, B, C):
cur += d
cur += (cur % c)
cur += b
if cur + D[-1] < t:
print("yes")
else:
print("no")
첫줄에 N 그 다음 N개의 줄에 speed / hour 와 달린 시간이 나온다. 이때 평균 속력을 출력하라.
(입력값 N이 -1일때까지)
n_line = int(input())
def total_miles(speeds, times):
total_miles = 0
prev_time = 0
for speed, time in zip(speeds, times):
total_miles += (time - prev_time) * speed
prev_time = time
return total_miles
while n_line != -1:
speeds, times = [], []
for _ in range(n_line):
speed, time = map(int, input().split())
speeds.append(speed)
times.append(time)
print(f'{total_miles(speeds, times)} miles')
n_line = int(input())
첫줄에는 친구가 맞은 문제 수가, 둘째 줄 세째 줄에는 나와 친구의 답안이 주어진다.
내가 맞을 수 있는 최대 문제 수를 출력하라.
correct = int(input())
my = input()
fr = input()
total = len(my)
same = 0
for m, f in zip(my, fr):
if m == f:
same += 1
if same > correct:
print(correct + (total - same))
else:
print(same + (total - correct))
두 문자가 주어질 때 그 문자를 출력하고
같은 자리는 . 다른 자리는 *를 아래에 출력하라.
N = int(input())
for _ in range(N):
st1 = input()
st2 = input()
print(st1)
print(st2)
for c1, c2 in zip(st1, st2):
if c1 == c2:
print('.', end='')
else:
print('*', end='')
print()
class Solution:
def rotate(self, A):
A[:] = zip(*A[::-1])
BJ_15641 SUPER SUPER (Bronze V)
input()
li = list(sorted(map(int, input().split())))
input()
def binary_search(li, x):
lo, hi = 0, len(li) - 1
while lo < hi:
mi = (hi + lo) // 2
if li[mi] < x:
lo = mi + 1
elif li[mi] > x:
hi = mi - 1
else:
return 1
return li[lo] == x
for n in map(int, input().split()):
print(1 if binary_search(li, n) else 0)
n, pieces = map(int, input().split())
li = []
for _ in range(n):
li.append(int(input()))
def count(li, length):
ret = 0
for n in li:
ret += n // length
return ret
def binary_search(li, x):
lo, hi = 0, max(li)
while lo < hi:
mi = (hi + lo + 1) // 2
if count(li, mi) < x:
hi = mi - 1
else:
lo = mi
return lo
print(binary_search(li, pieces))
_, length = map(int, input().split())
li = list(map(int, input().split()))
def total(li, cut):
ret = 0
for n in li:
ret += max(0, n - cut)
return ret
def binary_search(li, x):
lo, hi = 0, max(li)
while lo < hi:
mi = (hi + lo + 1) // 2
if total(li, mi) < x:
hi = mi - 1
else:
lo = mi
return lo
print(binary_search(li, length))
total, win = map(int, input().split())
z = int(100 * win / total)
if z >= 99:
print(-1)
else:
lo, hi = 0, 1000000000
while lo < hi:
mi = (lo + hi) // 2
if z < 100 * (win + mi) // (total + mi):
hi = mi
else:
lo = mi + 1
print(lo)
from bisect import insort
for _ in range(int(input())):
m = int(input())
print(str((m+1)//2))
nums = []
for t in range((m + 9) // 10):
for i, n in enumerate(map(int,input().split())):
insort(nums,n)
if i % 2 == 0:
print(nums[len(nums) // 2], end=' ')
if t % 2 == 1:
print()
if t%2==0:
print()
BJ_11053 가장 긴 증가하는 부분수열 (Silver II)
BJ_12015 가장 긴 증가하는 부분수열 2 (Gold II)
BJ_12738 가장 긴 증가하는 부분수열 3 (Gold II)
import bisect
input()
D = []
for e in map(int,input().split()):
if len(D) == 0 or e > D[-1]:
D += [e]
else:
D[bisect.bisect_left(D, e)] = e
print(len(D))
import sys
import bisect
li = sys.stdin.readlines()
for i in range(0, len(li), 2):
D = []
for e in map(int, li[i + 1].split()):
if len(D) == 0 or e > D[-1]:
D += [e]
else:
D[bisect.bisect_left(D, e)] = e
print(len(D))
# Top K most frequent elements
def topKFrequent(self, nums, k):
frq = defaultdict(list)
for key, cnt in Counter(nums).items():
frq[cnt].append(key)
res = []
for times in reversed(range(len(nums) + 1)):
res.extend(frq[times])
if len(res) >= k: return res[:k]
return res[:k]
LC_215 kth-largest-element-in-an-array/
def findKthLargest(self, li, k):
pivot = random.choice(li)
lo = [l for l in li if l < pivot]
mi = [e for e in li if e == pivot]
hi = [r for r in li if r > pivot]
if k <= len(hi):
return self.findKthLargest(hi, k)
elif (k - len(hi)) <= len(mi):
return mi[0]
else:
return self.findKthLargest(lo, k - len(hi) - len(mi))
def worked(li):
total = li[3] * 3600 + li[4] * 60 + li[5] - li[0] * 3600 - li[1] * 60 - li[2]
print(total // 3600, total % 3600 // 60, total % 60)
worked(list(map(int, input().split())))
worked(list(map(int, input().split())))
worked(list(map(int, input().split())))
print(eval(input()+input()+input()))
for _ in range(int(input())):
eq, ans = input().split('=')
print("correct" if eval(eq) == int(ans) else "wrong answer")
c = input()
while 1:
line = input()
if line == '=':
print(c)
break
b = input()
c = int(eval(str(c) + line + b))
import sys
for line in sys.stdin:
print(sum(map(int,line.split())))
import sys
input = sys.stdin.readline
n_test = int(input())
for _ in range(n_test):
a, b = map(int, input().split())
print(a + b)
BJ_11719 그대로 출력하기 2 (Bronze I)
import sys
print(sys.stdin.read())
import sys
for _ in range(3):
N = int(input())
li = [int(sys.stdin.readline()) for _ in range(N)]
total = sum(li)
if total > 0:
print('+')
elif total < 0:
print('-')
else:
print(0)
import sys
input = sys.stdin.readline
N = int(input())
li = []
a_win, b_win = 0, 0
for _ in range(N):
a, b = map(int, input().split())
if a > b:
a_win += 1
elif b > a:
b_win += 1
print(a_win, b_win)
import sys
for line in sys.stdin:
st = '1'
while True:
if int(st) % int(line) == 0:
print(len(st))
break
st += '1'
import sys
lines = sys.stdin.read().split()
for i, line in enumerate(lines):
if line == "<br>":
print()
elif line == "<hr>":
if i != 0 and lines[i-1] not in ("<br>", "<hr>"):
print()
print("-" * 80)
else:
print(line, end=" ")
from copy import copy
for _ in range(int(input())):
total = int(input())
li = list(map(int, input().split()))
for d in range(1, 100000):
if sum(li) > total:
print(d)
break
old = copy(li)
for i in range(6):
li[i] = old[i] + old[(i + 1) % 6] + old[(i + 3) % 6] + old[(i + 5) % 6]
BJE_15858 Simple Arithmetic (Bronze III)
from decimal import *
a,b,c=map(Decimal,input().split())
print(a*b/c)
from decimal import *
getcontext().prec = 10000
a, b = map(Decimal, input().split())
print(f"{a / b:.1000f}")
from decimal import *
getcontext().prec = 1200
a, b = list(map(Decimal, input().split()))
print(format(a ** b, 'f'))
LC_470 implement-rand10-using-rand7 (Medium)
class Solution:
def rand10(self):
rand40 = 40
while rand40 >= 40:
rand40 = (rand7() - 1) * 7 + rand7() - 1
return rand40 % 10 + 1
LC_478 generate-random-point-in-a-circle (Medium)
import math
import random
class Solution:
def __init__(self, radius, x_center, y_center):
self.radius = radius
self.x_center = x_center
self.y_center = y_center
random.seed()
def randPoint(self):
degree = random.uniform(0, 2 * math.pi)
dist = (2 * random.uniform(0, self.radius ** 2 / 2.0)) ** (1/2.0)
x = dist * math.cos(degree)
y = dist * math.sin(degree)
return [self.x_center + x, self.y_center + y]
import re
for _ in range(int(input())):
print("Infected!" if re.match('^[A-F]?A+F+C+[A-F]?$', input()) else "Good")
import re
input()
print(sum([int(d) for d in re.findall('\d+', input())]))
while True:
line = input()
if line == '.':
break
stk = []
for ch in line:
if ch == '(' or ch == '[':
stk.append(ch)
elif ch == ')':
if not stk or stk[-1] == '[':
print("no")
break
elif stk[-1] == '(':
stk.pop()
elif ch == ']':
if not stk or stk[-1] == '(':
print("no")
break
elif stk[-1] == '[':
stk.pop()
else:
print("no" if stk else "yes")
bar_razor = list(input())
answer = 0
stk = []
for i in range(len(bar_razor)):
if bar_razor[i] == '(':
stk.append('(')
else:
if bar_razor[i - 1] == '(':
stk.pop()
answer += len(stk)
else:
stk.pop()
answer += 1
print(answer)
def largest_rect(heights):
hws, mx_area = [], 0
for i, h in enumerate(heights):
width = 0
while len(hws) and h < hws[-1][0]:
width += hws[-1][1]
mx_area = max(mx_area, width * hws[-1][0])
hws.pop()
hws.append([h, width + 1])
while hws:
width += hws[-1][1]
mx_area = max(mx_area, width * hws.pop()[0])
return mx_area
line = int(input())
heights = [int(input()) for _ in range(line)]
print(largest_rect(heights))
BJ_6549 히스토그램에서 가장 큰 직사각형 (Platinum V)
def largest_rect(heights):
hws, mx_area = [], 0
for i, h in enumerate(heights):
width = 0
while len(hws) and h < hws[-1][0]:
width += hws[-1][1]
mx_area = max(mx_area, width * hws[-1][0])
hws.pop()
hws.append([h, width + 1])
while hws:
width += hws[-1][1]
mx_area = max(mx_area, width * hws.pop()[0])
return mx_area
while True:
line = input()
if line == '0':
break
heights = list(map(int, line.split()))[1:]
print(largest_rect(heights))
import sys
from collections import deque
input = sys.stdin.readline
N = int(input())
dq = deque()
for i in range(N):
cmd = list(input().split())
if cmd[0] == 'push_front':
dq.appendleft(cmd[1])
elif cmd[0] == 'push_back':
dq.append(cmd[1])
elif cmd[0] == 'pop_front':
print("-1" if len(dq) == 0 else dq.popleft())
elif cmd[0] == 'pop_back':
print("-1" if len(dq) == 0 else dq.pop())
elif cmd[0] == 'front':
print("-1" if len(dq) == 0 else dq[0])
elif cmd[0] == 'back':
print("-1" if len(dq) == 0 else dq[-1])
elif cmd[0] == 'size':
print(len(dq))
elif cmd[0] == 'empty':
print(1 if len(dq) == 0 else 0 )
import sys
from collections import deque
input = sys.stdin.readline
dq = deque()
for _ in range(int(input())):
num = int(input())
if num == 0:
dq.pop()
else:
dq.append(num)
print(sum(dq))
from collections import deque
deck = deque(range(1, int(input()) + 1))
while len(deck) > 1:
deck.popleft()
deck.append(deck.popleft())
print(deck[0])
from collections import deque
N = int(input())
student = list(map(int, input().split()))
result = deque()
for i, move in enumerate(student):
result.rotate(move)
result.append(i + 1)
result.rotate(-move)
print(*result)
from collections import deque
for _ in range(int(input())):
N, M = map(int, input().split())
weight = deque(map(int, input().split()))
index = deque(range(N))
res = 1
while True:
if index[0] == M and weight[0] == max(weight):
break
else:
if weight[0] == max(weight):
weight.popleft()
index.popleft()
res += 1
else:
weight.append(weight.popleft())
index.append(index.popleft())
print(res)
from collections import deque
import sys
N = int(input())
samples = deque()
for _ in range(N):
tokens = sys.stdin.readline().split()
if tokens[0] == 'push':
samples.append(tokens[1])
elif tokens[0] == 'pop':
print(samples.popleft() if samples else -1)
elif tokens[0] == 'size':
print(len(samples))
elif tokens[0] == 'empty':
print(0 if samples else 1)
elif tokens[0] == 'front':
print(samples[0] if samples else -1)
elif tokens[0] == 'back':
print(samples[-1] if samples else -1)
import heapq
import sys
input = sys.stdin.readline
heap = []
for _ in range(int(input())):
num = int(input())
if num != 0:
heapq.heappush(heap, (-num))
else:
if len(heap):
print(-1 * heapq.heappop(heap))
else:
print(0)
input()
li = list(map(int,input().split()))
if max(li) <= 0:
print(max(li))
else:
cur_sum = 0
max_sum = 0
for n in li:
cur_sum += n
if cur_sum < 0:
cur_sum = 0
max_sum = max(cur_sum, max_sum)
print(max_sum)
import sys
import heapq
input=sys.stdin.readline
for _ in range(int(input())):
numbers = set()
minH, maxH = [],[]
for i in range(int(input())):
s=input().split()
if s[0]=='I':
heapq.heappush(minH,(int(s[1]),i))
heapq.heappush(maxH,(-int(s[1]),i))
numbers.add(i)
elif s[1]=='1':
while maxH and not maxH[0][1] in numbers:
heapq.heappop(maxH)
if maxH:
numbers.remove(maxH[0][1])
heapq.heappop(maxH)
else:
while minH and not minH[0][1] in numbers:
heapq.heappop(minH)
if minH:
numbers.remove(minH[0][1])
heapq.heappop(minH)
while minH and minH[0][1] not in numbers:
heapq.heappop(minH)
while maxH and maxH[0][1] not in numbers:
heapq.heappop(maxH)
print(f'{-maxH[0][0]} {minH[0][0]}' if maxH and minH else 'EMPTY')
import heapq
n, m = int(input()), int(input())
G = [[] for _ in range(n)]
for _ in range(m):
s, e, c = map(int, input().split())
G[s-1].append([e-1, c])
G[e-1].append([s-1, c])
key = [0] + [float('inf')] * (n - 1)
visited = [False] * n
pq = []
heapq.heappush(pq, (0, 0))
result = 0
while pq:
k, u = heapq.heappop(pq)
if visited[u]:
continue
visited[u] = True
result += k
for dest, w in G[u]:
if not visited[dest] and w < key[dest]:
key[dest] = w
heapq.heappush(pq, (key[dest], dest))
print(result)
import sys
from heapq import *
input = sys.stdin.readline
n,k = map(int,input().split())
pq = [(0, i) for i in range(k)]
arr, ids = [],[]
for i in range(n):
id_,buy = map(int,input().split())
time, kiosk = heappop(pq)
heappush(pq,(time + buy, kiosk))
arr.append((time + buy, kiosk, i+1))
ids.append(id_)
arr.sort(key=lambda x:(x[0],-x[1]))
s = 0
for i in range(n):
s += ids[arr[i][2] - 1] * (i + 1)
print(s)
LC_21 merge-two-sorted-lists (Easy)
class Solution:
def mergeTwoLists(self, l1: ListNode, l2: ListNode) -> ListNode:
dummy = cur = ListNode(0)
while l1 and l2:
if l1.val < l2.val:
cur.next = l1
l1 = l1.next
else:
cur.next = l2
l2 = l2.next
cur = cur.next
cur.next = l1 or l2
return dummy.next
class Solution:
def rotateRight(self, head: ListNode, k: int) -> ListNode:
if not head:
return None
old_last = head
length = 1
while old_last.next:
old_last = old_last.next
length += 1
k = k % length
old_last.next = head
new_last = head
for _ in range(length - k - 1):
new_last = new_last.next
answer = new_last.next
new_last.next = None
return answer
class Solution:
def addTwoNumbers(self, l1, l2):
carry = 0;
res = n = ListNode(0);
while l1 or l2 or carry:
if l1:
carry += l1.val
l1 = l1.next;
if l2:
carry += l2.val;
l2 = l2.next;
carry, val = divmod(carry, 10)
n.next = n = ListNode(val);
return res.next
LC_19 remove-nth-node-from-end-of-list (medium)
class Solution:
def removeNthFromEnd(self, head, n):
fast = slow = head
for _ in range(n):
fast = fast.next
if not fast:
return head.next
while fast.next:
fast = fast.next
slow = slow.next
slow.next = slow.next.next
return head
LC_109 convert-sorted-list-to-binary-search-tree (Medium)
class Solution:
def sortedListToBST(self, head):
if not head:
return
if not head.next:
return TreeNode(head.val)
slow, fast = head, head.next.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
tmp = slow.next
slow.next = None
root = TreeNode(tmp.val)
root.left = self.sortedListToBST(head)
root.right = self.sortedListToBST(tmp.next)
return root
Walk # Vertices may repeat. Edges may repeat (Closed or Open)
Trail # Vertices may repeat. Edges cannot repeat (Open)
Circuit # Vertices may repeat. Edges cannot repeat (Closed)
Path # Vertices cannot repeat. Edges cannot repeat (Open)
Cycle # Vertices cannot repeat. Edges cannot repeat (Closed)
Hamiltonian # Visits every vertex in the graph
Eulerian # Visits every edge in the graph
# Directed
DAGs # Directed acyclic graphs are directed graphs with no cycle
Weakly Connected # Undirected version of directed graph is connected
Strongly Connected # Directed graph G is strongly connected a path exists for all ordered pair vertices
SCC # Strongly connected components is maximal strongly connected piece
# Undirected
Connected # G is connected if for any pair of vertices v, w there is a path from v to w
CC Connected components is maximal connected piece
What is indegree of 2?
Is the cycle in the graph? (T/F)
Is the graph directed? (T/F)
Shortest Path from 0 to 5
How many edges are there?
What is indegree of 5?
How many vertices are there?
What is the biggest edge in the graph?
What is the smallest cycle sum?
What is the outdegree of 0?
Tree edge # solid edge included in the DFS output tree (pre u < pre v < post v < post u)
Back edge # leads to an ancestor (pre v < pre u < post u < post v)
Cross edge # leads to neither anc. or des (pre v < post v < pre u < post(u)
What is the root?
How many vertices are there?
How many children does node 2 have?
What is the parent of 6?
How many leaves are there?
What is the depth of 10?
How many children does node 7 have?
How many edges are there?
What is the depth of the tree?
How many vertices have 2 children?
BJE_10090 Counting Inversion (Gold I)
class SegmentTree:
def __init__(self, nums):
self.N = len(nums)
self.tree = [0] * self.N + nums
for i in range(self.N - 1, 0, -1):
self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1]
def update(self, i, val):
n = self.N + i
self.tree[n] = val
while n > 1:
self.tree[n>>1] = self.tree[n] + self.tree[n^1]
n >>= 1
def sumRange(self, i, j):
m, n = self.N + i, self.N + j
res = 0
while m <= n:
if m & 1:
res += self.tree[m]
m += 1
m >>= 1
if n & 1 ==0:
res += self.tree[n]
n -= 1
n >>= 1
return res
N, res = int(input()), 0
st = SegmentTree([0] * (N + 1))
for n in map(int, input().split()):
st.update(n, 1)
res += st.sumRange(n + 1, N)
print(res)
class SegmentTree:
def __init__(self, nums):
self.N = len(nums)
self.tree = [0] * self.N + nums
for i in range(self.N - 1, 0, -1):
self.tree[i] = self.tree[i<<1] + self.tree[i<<1|1]
def update(self, i, val):
n = self.N + i
self.tree[n] = val
while n > 1:
self.tree[n>>1] = self.tree[n] + self.tree[n^1]
n >>= 1
def sumRange(self, i, j):
m, n = self.N + i, self.N + j
res = 0
while m <= n:
if m & 1:
res += self.tree[m]
m += 1
m >>= 1
if n & 1 ==0:
res += self.tree[n]
n -= 1
n >>= 1
return res
N, M, K = map(int, input().split())
st = SegmentTree([int(input()) for _ in range(N)])
for i in range(M + K):
typ, a, b = map(int, input().split())
if typ == 1:
st.update(a - 1, b)
else:
print(st.sumRange(a - 1, b - 1))
import sys,math
class SegTree:
def __init__(self, a,hi):
self.tree=[9000000000]*(hi<<1)
self.maxt=[0]*(hi<<1)
self.h = hi
self.tree[hi:hi+len(a)] = self.maxt[hi:hi+len(a)] = a
for i in range(hi-1,0,-1):
t=i<<1
m=0
a=self.tree[t]
b=self.tree[t+1]
if a>b:m=b
else:m=a
self.tree[i]=m
a=self.maxt[t]
b=self.maxt[t+1]
if a<b:m=b
else:m=a
self.maxt[i]=m
def q(self,left,right):
min_r=[]
max_r=[]
left+=h
right+=h
while left<right:
if left%2:
min_r+=[self.tree[left]]
max_r+=[self.maxt[left]]
left+=1
if right%2==0:
min_r+=[self.tree[right]]
max_r+=[self.maxt[right]]
right-=1
left//=2
right//=2
if left==right:
min_r+=[self.tree[left]]
max_r+=[self.maxt[left]]
return [min(min_r),max(max_r)]
input=sys.stdin.readline
n,m=map(int,input().split())
p=[int(input())for i in range(n)]
h=1<<math.ceil(math.log2(n))
tree=SegTree(p,h)
for i in sys.stdin:
a,b=map(int,i.split())
print(*tree.q(a-1,b-1))
import sys
input = sys.stdin.readline
class SegmentTree:
def __init__(self, n):
self.h = n.bit_length()
self.seg = [0] * 2*n
self.lazy = [0] * n
self.size = [1] * 2*n
for i in reversed(range(1, n)):
self.size[i] = 2 * self.size[2*i]
def apply(self, p):
self.seg[p] = self.size[p] - self.seg[p]
if p < n:
self.lazy[p] ^= 1
def up(self, p):
while p > 1:
p >>= 1
self.seg[p] = self.seg[2*p] + self.seg[2*p + 1]
if self.lazy[p] == 1:
self.seg[p] = self.size[p] - self.seg[p]
def down(self, p):
for i in reversed(range(1, self.h + 1)):
pp = p >> i
if self.lazy[pp] != 0:
self.apply(2*pp)
self.apply(2*pp + 1)
self.lazy[pp] = 0
def update(self, l, r):
l += n
r += n
l0, r0 = l, r
while l < r:
if l & 1:
self.apply(l)
l += 1
if r & 1:
r -= 1
self.apply(r)
l >>= 1
r >>= 1
self.up(l0)
self.up(r0 - 1)
def query(self, l, r):
l += n
r += n
self.down(l)
self.down(r - 1)
res = 0
while l < r:
if l & 1:
res += self.seg[l]
l += 1
if r & 1:
r -= 1
res += self.seg[r]
l >>= 1
r >>= 1
return res
n, m = map(int, input().split())
st = SegmentTree(n)
for _ in range(m):
q = list(map(int, input().split()))
if q[0] == 0:
st.update(q[1] - 1, q[2])
else:
print(st.query(q[1] - 1, q[2]))
BJ_2869 달팽이는 올라가고 싶다 (Bronze II)
import math
a, b, c = map(int, input().split())
print(math.ceil((c - a) / (a - b)) + 1)
import math
a, b = int(input()), int(input())
print(a * 2 + 2 * b * math.pi)
import math
n = int(input())
A = int(input())
B = int(input())
C = int(input())
D = int(input())
print(n - max(math.ceil(A / C), math.ceil(B / D)))
BJ_13136 Do Not Touch Anything (Bronze IV)
import math
a, b, c = map(int, input().split())
print(math.ceil(a / c) * math.ceil(b / c))
import math
a, b, c = map(int, input().split())
team = min(a // 2, b)
c = max(0, c - (a - team * 2) - (b - team))
print(team - math.ceil(c / 3))
import math
n = int(input())
print(n * n * math.pi)
print(n * n * 2)
import itertools
li = [int(input()) for _ in range(9)]
for l in itertools.combinations(li, 7):
if sum(l) == 100:
print(*sorted(l), sep='\n')
break
import itertools
n, m = map(int, input().split())
li = list(map(int, input().split()))
ret = 0
for l in itertools.combinations(li, 3):
if ret < sum(l) <= m:
ret = sum(l)
print(ret)
import sys
input = sys.stdin.readline
n = int(input())
total = 0
for _ in range(n):
total += int(input())
print(total - n + 1)
import math
t = int(input());
for _ in range(t):
a,b = map(int, input().split())
print(int(a * b / math.gcd(a,b)))
첫째 줄에 n이 주어진다.
반지름이 n인 원의 넓이를 출력하라.
그 다음 줄에 n * n * 2 를 출력하라.
import math
n = int(input())
print(n * n * math.pi)
print(n * n * 2)
높이 h와 각도 theta가 주어질 때 사다리의 최소 길이를 구하여라. (ceil)
import math
a, theta = map(int, input().split())
print(math.ceil(a / math.sin(theta / 180 * math.pi)))
n_test개의 줄에 N과 N개의 정수가 주어진다.
이때 짝이 없는 정수를 출력하라.
n_test = int(input())
for test in range(1, n_test + 1):
N = int(input())
ret = 0
for x in map(int, input().split()):
ret ^= x
print(f"Case #{test}: {ret}")
import math
n_shot = int(input())
for _ in range(n_shot):
v, theta, x, h1, h2 = map(float, input().split())
hit_t = x / (v * math.cos(theta / 180 * math.pi))
hit_y = v * hit_t * math.sin(theta / 180 * math.pi) - 9.8/2 * hit_t ** 2
if h1 + 1 <= hit_y <= h2 - 1:
print('Safe')
else:
print('Not Safe')
#
#
#
Zero, negative, and fractional exponents
-2 ** 3
-5 ** -2
0**0
10**3
1000000**0
4**0.5
27**(1/3)
16**(3/4)
4**(-0.5)
8**(-2/3)
a, b, c, d, e = map(int, input().split())
print((a ** 2 + b ** 2 + c ** 2 + d ** 2 + e ** 2) % 10)
BJE_15610 Abbey Courtyard (Bronze IV)
print(int(input()) ** 0.5 * 4)
d, w, h = map(int, input().split())
x = (d ** 2 / (w ** 2 + h ** 2)) ** 0.5
print(int(x * w), int(x * h))
for i in range(int(input())):
a,b = map(int,input().split())
ans = pow(a,b,10)
print(10 if ans == 0 else ans)
n, w, h = map(int, input().split())
for _ in range(n):
a = int(input())
if a ** 2 <= w ** 2 + h ** 2:
print('DA')
else:
print('NE')
BJ_2903 중앙 이동 알고리즘 (Bronze III)
a = int(input())
print((2 ** a + 1) ** 2)
a, b = map(int, input().split())
print(a ** b)
n = int(input())
print(f'{2 ** (-n):.{n}f}')
for i in range(int(input())):
sides = sorted(map(int, input().split()))
if sides[0] ** 2 + sides[1] ** 2 + sides[2] ** 2 == max(sides) ** 2 * 2:
print(f'Scenario #{i + 1}:\nyes')
else:
print(f'Scenario #{i + 1}:\nno')
print()
BJ_1834 나머지와 몫이 같은 수 (Bronze I)
N=int(input())
print((N**3-N)//2)
N = int(input())
print(N//5 + N//25 + N//125)
정사각형의 목장이 있다.
목장의 넓이가 주어질 때 목장을 둘러싸는 fence의 길이를 구하라.
n = int(input())
print((n ** 0.5) * 4)
첫 줄에 n 이 주어진다.
n^(1 / n) 을 출력하라.
n = float(input())
print(n ** (1/n))
다음과 같은 규칙이 있을때 n + 1번째 그림의 점의 개수를 구하여라
a = int(input())
print((2 ** a + 1) ** 2)
from math import ceil, log
line = int(input())
print(int(ceil(log(line, 2) + 1)))
Introduction to number systems and binary
Converting from decimal to binary
Converting larger number from decimal to binary
Hexadecimal number system
Converting from decimal to hexadecimal representation
Converting directly from binary to hexadecimal
int('0b1111') # 15 (2 → 10)
int('A0', 16) # 160 (16 → 10)
bin(11) # '0b1011' (10 → 2)
oct(15) # '0o17' (10 → 8)
hex(10) # '0xA' (10 → 16)
# table
print('2', '10', '16')
for i in range(50):
print(bin(i)[2:], '\t', i, '\t', hex(i)[2:])
15 to Binary
12 to Hexadecimal
0b1011 + 0b1111 to binary
0b1011 to Hexadecimal
0x1BC0 to Decimal
0xBC to Binary
0o163 + 0o53 to Octet
0x12 // 0x6 to Decimal
0b1101 * 0b111 to Binary
4200 to Hexadecimal
print(int(input(), 16))
a = int(input(), 2)
print(bin(a * 17)[2:])
n = int(input(), 8)
print(bin(n)[2:])
a, b = int(input(), 2), int(input(), 2)
print(bin(a * b)[2:])
n = int(input())
print(0 if (n & (n - 1)) else 1)
N = int(input())
ret = count = 0
while N > 0:
ret += N % 9 * pow(10, count)
count += 1
N //= 9
print(ret)
BJ 13877 이건 무슨 진법이지? (Bronze III)
for _ in range(int(input())):
a, b = input().split()
print(a, end = ' ')
if '8' in b or '9' in b:
print(0, end = ' ')
else:
print(int(b, 8), end = ' ')
print(int(b, 10), int(b, 16))
ch2int = {'-':0, '\\':1, '(':2, '@':3, '?':4, '>':5, '&':6, '%':7, '/':-1}
while True:
string = input()
if string == '#':
break
ret = 0
for ch in string:
ret *= 8
ret += ch2int[ch]
print(ret)
n = int(input())
for _ in range(n):
x = int(input())
n = 0
while x != 0:
if x & 1:
print(n, end=' ')
n += 1
x //= 2
print()
a, b = input().split()
print(int(a, int(b)))
BJ_6679 싱기한 네자리 숫자 (Bronze II)
def sum_digit(dec, n):
ret = 0
while n != 0:
ret += n % dec
n //= dec
return ret
for n in range(1000, 10000):
if sum_digit(10, n) == sum_digit(12, n) == sum_digit(16, n):
print(n)
print(bin(int(input()))[2:])
a, b = map(int, input().split())
conv = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ"
ret = ""
while a != 0:
ret = conv[a % b] + ret
a //= b
print(ret)
BJ_11816 8진수, 10진수, 16진수 (Bronze I)
line = input()
if line[0] == '0':
if line[1] == 'x':
print(int(line, 16))
else:
print(int(line, 8))
else:
print(line)
import sys
import os
a = bytearray(2**22)
unstdin = os.fdopen(sys.stdin.fileno(), 'rb', 1000000)
while True:
b = 0
while True:
ch = unstdin.read(1)
if b'0' <= ch <= b'9':
b = 10*b+int(ch)
elif ch == b' ':
break
else:
x, y = b % 8, b // 8
if not a[y] & (1<<x):
print(b, end = '')
exit()
x, y = b % 8, b // 8
if not a[y] & (1<<x):
print(b, end = ' ')
a[y] |= (1<<x)
2진법으로 들어 온 수를 8진법으로 출력하라.
num = int(input(), 2)
print(oct(num)[2:])
print(1 ^ 4)
print(4 ^ 6)
print(2 | 5)
print(3 | 6)
print(4 & 5)
print(8 & 3)
print(11 | 13)
print(7 & 5)
print(12 & 14)
print(13 ^ 10)
n&-n # Get lowest set bit
(n&(n-1))==0 # Check power of two
a, b = map(int, input().split())
c, d = map(int, input().split())
e, f = map(int, input().split())
print(a ^ c ^ e, b ^ d ^ f)
BJ 15917 노솔브 방지문제야!! (Bronze III)
import sys
input = sys.stdin.readline
N = int(input())
for _ in range(N):
a = int(input())
if a&(-a) != a:
print('0')
else:
print('1')
BJ_12833 XORXORXOR (Bronze III)
a, b, c = map(int, input().split())
for _ in range(c % 2):
a ^= b
print(a)
import sys
input = sys.stdin.readline
n, m = map(int, input().split())
words = [0 for i in range(n)]
for i in range(n):
for ch in input().rstrip():
words[i] |= 1 << (ord(ch) - 97)
alpha = 0xffffffff
for _ in range(m):
o, x = input().split()
if o == '1':
alpha &= ~(1 << ord(x)-97)
elif o == '2':
alpha |= (1 << ord(x)-97)
print(sum(1 for word in words if (word & alpha) == word))
3개의 꼭짓점의 좌표가 주어질 때 나머지 한개의 꼭짓점의 좌표를 구하여라.
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
print(x1 ^ x2 ^ x3, y1 ^ y2 ^ y3)
def countBits(self, num) -> List[int]:
ret = [0] * (num + 1)
for i in range(num + 1):
ret[i] = ret[i // 2] + i % 2
return ret
숫자 1-6으로 만들 수 있는 3자리 숫자의 개수
숫자 1-6으로 만들 수 있는 3자리 짝수의 개수
소문자 알파벳 3자와 숫자 3 개로 만들 수 있는 아이디의 개수
s = input()
ret = 1
for i, ch in enumerate(s):
if ch == 'd':
if i != 0 and s[i - 1] == 'd':
ret *= 9
else:
ret *= 10
else:
if i != 0 and s[i - 1] == 'c':
ret *= 25
else:
ret *= 26
print(ret)
s = input()
ret = 1
for i, ch in enumerate(s):
if ch == 'd':
if i != 0 and s[i - 1] == 'd':
ret *= 9
else:
ret *= 10
else:
if i != 0 and s[i - 1] == 'c':
ret *= 25
else:
ret *= 26
ret %= 1000000009
print(ret)
n = int(input())
print(n * (n - 1) * (n -2) * (n - 3) // 24)
import math
a, b = map(int, input().split())
print(math.comb(a, b))
import math
N = int(input())
for _ in range(N):
a, b = map(int, input().split())
print(math.comb(b, a))
from math import comb
N = int(input())
li = list(map(int, input().split()))
pick = int(input())
print(sum(comb(n, pick) for n in li) / comb(sum(li), pick))
import math
while True:
a, b = map(int, input().split())
if a == b == 0:
break
print(math.comb(a, b))
from itertools import combinations
while True:
line = input()
if line == "0":
break
li = line.split()[1:]
for comb in combinations(li, 6):
print(" ".join(comb))
print()
from itertools import permutations
N = int(input())
A = list(map(int, input().split()))
a, s, m, d = map(int, input().split())
mn, mx = float('inf'), -float('inf')
for p in set(permutations('+'*a+'-'*s+'*'*m+'/'*d)):
r = A[0]
for i in range(1, N):
r = {'+': r+A[i], '-': r-A[i], '*': r*A[i], '/': int(r/A[i])}[p[i-1]]
mn = min(mn, r)
mx = max(mx, r)
print(mx)
print(mn)
from itertools import combinations
n, m = map(int, input().split())
li = sorted(input().split())
for c in combinations(li, n):
count = 0
for letter in c:
if letter in "aeiou":
count += 1
if (count >= 1) and (count <= n-2):
print(*c, sep ='')
n개의 꼭지점을 가진 다각형이 있다.
이 때 모든 선분의 교차점의 개수를 출력하라. 단 3개 이상의 선분은 한 점에서 만나지 않는다.
import math
def nCr(n,r):
if r > n:
return 0
f = math.factorial
return f(n) // f(r) // f(n-r)
n = int(input())
print(nCr(n, 4))
import math
while True:
a, b = map(int, input().split())
if a == b == 0:
break
print(math.comb(a, b))
Range, variance and standard deviation as measures of dispersion
BJE_16693 Pizza Deal (Bronze IV)
import math
a, p1 = map(int, input().split())
r, p2 = map(int, input().split())
if a * p2 < r * r * math.pi * p1:
print('Whole pizza')
else:
print('Slice of pizza')
BJ_14264 정육각형과 삼각형 (Bronze IV)
import math
s = int(input())
print(math.sin(60 * math.pi / 180) * s ** 2 / 2)
def dist(p1, p2):
ax, ay = p1
bx, by = p2
return (ax - bx) ** 2 + (ay - by) ** 2
for _ in range(int(input())):
P = [tuple(map(int,input().split())) for i in range(4)]
P.sort()
ans = dist(P[0], P[3]) == dist(P[1], P[2]) and dist(P[0], P[1]) == dist(P[0], P[2])
print(int(ans))
def ccw(x1, y1, x2, y2, x3, y3):
total = (x2-x1) * (y3-y1) - (y2-y1) * (x3-x1)
return (total > 0) - (total < 0)
x1, y1 = map(int, input().split())
x2, y2 = map(int, input().split())
x3, y3 = map(int, input().split())
print(ccw(x1, y1, x2, y2, x3, y3))
def ccw(x1, y1, x2, y2, x3, y3):
total = (x2-x1) * (y3-y1) - (y2-y1) * (x3-x1)
return (total > 0) - (total < 0)
x1, y1, x2, y2 = map(int, input().split())
x3, y3, x4, y4 = map(int, input().split())
if ccw(x1, y1, x2, y2, x3, y3) * ccw(x1, y1, x2, y2, x4, y4) < 0 and \
ccw(x3, y3, g, h, x1, y1)*ccw(x3, y3, g, h, x2, y2)<0:
print(1)
else:
print(0)
def ccw(x1, y1, x2, y2, x3, y3):
total = (x2-x1) * (y3-y1) - (y2-y1) * (x3-x1)
return (total > 0) - (total < 0)
x1, y1, x2, y2 = map(int, input().split())
x3, y3, x4, y4 = map(int, input().split())
D1, D2 = ccw(x1, y1, x2, y2, x3, y3), ccw(x1, y1, x2, y2, x4, y4)
D3, D4 = ccw(x3, y3, x4, y4, x1, y1), ccw(x3, y3, x4, y4, x2, y2)
if D1 == D2 == 0:
lo, hi = min((x1, y1), (x2, y2)), max((x1, y1), (x2, y2))
if lo <= min((x3, y3), (x4, y4)) <= hi:
print(1)
else:
print(0)
elif D1 * D2 <= 0 and D3 * D4 <= 0:
print(1)
else:
print(0)
def ccw(p1, p2, p3):
v, u = (p2[0] - p1[0], p2[1] - p1[1]), (p3[0] - p2[0], p3[1] - p2[1])
if v[0] * u[1] > v[1] * u[0]:
return True
return False
def convex_hull(points):
convex = []
for p3 in points:
while len(convex) >= 2:
p1, p2 = convex[-2], convex[-1]
if ccw(p1, p2, p3):
break
convex.pop()
convex.append(p3)
return len(convex)
n, answer = int(input()), -2
points = list(sorted(tuple(map(int, input().split())) for _ in range(n)))
answer += convex_hull(points)
points.reverse()
answer += convex_hull(points)
print(answer)
n_test = int(input())
for i in range(n_test):
li = list(map(int, input().split()))
ret = 0
for i in range(1, len(li) - 1):
ret += max(0, li[i] - li[i - 1] * 2)
print(ret)
a, b, c, d = map(int, input().split())
s = sum([a, b, c, d]) / 2
print(((s - a) * (s - b) * (s - c) * (s - d)) ** 0.5)
import math
while True:
a, b = map(int, input().split())
if a == b == 0:
break
print((a * a * a - 6 * b / math.pi) ** (1/3))
Q. 36 =
p, q = map(int, input().split())
for i in range(1, p + 1):
if p % i == 0:
q -= 1
if q == 0:
print(i)
break
else:
print(0)
li = list(map(int, input()))
if sum(li) % 3 != 0 or 0 not in li:
print(-1)
else:
print(*sorted(li, reverse=True), sep='')
N = int(input())
li = sorted(map(int, input().split()))
print(li[0] * li[-1])
n = int(input())
for i in range(2, n + 1):
while n % i == 0:
n //= i
print(i)
def is_prime(n):
if n < 2:
return False
for i in range(2, int(n ** 0.5) + 1):
if n % i == 0:
return False
return True
N = int(input())
arr = list(map(int, input().split()))
ret = 0
for n in arr:
if is_prime(n):
ret += 1
print(ret)
BJ_11502 세 개의 소수 문제 (Silver III)
from itertools import combinations_with_replacement
is_prime = [False, False] + [True] * (1000)
primes = []
for i in range(2, len(is_prime)):
if is_prime[i]:
primes.append(i)
for j in range(2 * i, len(is_prime), i):
is_prime[j] = False
for _ in range(int(input())):
n = int(input())
for a, b, c in combinations_with_replacement(primes, 3):
if a + b + c == n:
print(a, b, c)
break
else:
print(0)
N = int(input())
li = list(map(int, input().split()))
ret = 0
for n in li:
if is_prime(n):
ret += 1
print(ret)
is_prime = [False, False, True] + [True] * (123456 * 2)
for i in range(2, len(is_prime)):
if is_prime[i]:
for j in range(2 * i, len(is_prime), i):
is_prime[j] = False
while True:
N = int(input())
if N == 0:
break
count = 0
for n in range(N + 1, N * 2 + 1):
if is_prime[n]:
count += 1
print(count)
is_prime = [False, False, True] + [True] * (7368788)
count = int(input())
for i in range(2, len(is_prime)):
if is_prime[i]:
count -= 1
if count == 0:
print(i)
for j in range(2 * i, len(is_prime), i):
is_prime[j] = False
is_prime = [False, False, True] + [True] * (123456 * 2)
for i in range(2, len(is_prime)):
if is_prime[i]:
for j in range(2 * i, len(is_prime), i):
is_prime[j] = False
n = int(input())
for k in range(n):
n = int(input())
for i in range(n//2, n + 1):
if is_prime[i] and is_prime[n - i]:
print(f'{is_prime[n - i]} {is_prime[i]}')
break
M, N = int(input()), int(input())
li = []
for n in range(M, N + 1):
if is_prime(n):
li.append(n)
if len(li) == 0:
print(-1)
else:
print(sum(li))
print(min(li))
mn, mx = map(int, input().split())
li = [1] * (mx - mn + 1)
for root in range(2, int(mx ** 0.5) + 1):
square = root ** 2
for n in range(max(mn // square, 1), mx // square + 1):
if mn <= square * n <= mx:
li[square * n - mn] = 0
print(sum(li))
Greatest common factor exercise
Least common multiple exercise
Least common multiple exercise 2
Least common multiple exercise 3
# 50 26 GCD
is 2 prime?
11이 소수인가?
111이 소수인가?
12 36 GCD
15 48 LCM
9 17 GCD
108 18 LCM
24 111 GCD
13 93 LCM
36 88 GCD
def GCD(x, y):
while(y):
x, y = y, x % y
return x
input()
s = list(map(int, input().split()))
g = GCD(s[0], GCD(s[1], s[-1]))
for i in range(1, (g // 2) + 1):
if g % i == 0:
print(i)
print(g)
def GCD(x, y):
while y :
x, y = y, x % y
return x
def LCM(a, b):
return a * b // GCD(a, b)
for _ in range(int(input())):
a, b = map(int, input().split())
print(LCM(a, b), GCD(a, b))
def divisors(num):
li = [1]
for i in range(2, int(num ** 0.5 + 1)):
if num % i == 0:
li.append(i)
if i != num // i:
li.append(num // i)
return sorted(li)
while True:
n = int(input())
if n == -1:
break
divs_n = divisors(n)
if sum(divs_n) == n:
print(n, '=', ' + '.join(map(str, divs_n)))
else:
print(f"{n} is NOT perfect.")
def GCD(a, b):
while(b):
a, b = b, a % b
return a
def LCM(a, b):
return a * b // GCD(a, b)
a, b = map(int, input().split())
print(GCD(a, b), LCM(a, b))
def GCD(a, b):
while(b):
a, b = b, a % b
return a
def LCM(a, b):
return a * b // GCD(a, b)
for _ in range(int(input())):
a, b = map(int, input().split())
print(LCM(a, b))
def GCD(a, b):
while(b):
a, b = b, a % b
return a
def LCM(a, b):
return a * b // GCD(a, b)
a, b = map(int, input().split())
print(LCM(a, b))
from itertools import combinations
def GCD(a, b):
while(b):
a, b = b, a % b
return a
n = int(input())
for _ in range(n):
li = list(map(int, input().split()))
print(sum(GCD(a, b) for a, b in combinations(li[1:], 2)))
n = int(input())
print(n * (n + 1) // 2)
a,b = map(int,input().split())
print((a + b) * (abs(a - b) + 1) // 2)
n = int(input())
res = n // 3 - 1
print(res * (res - 1) // 2)
n = int(input())
print((n + 1) * (n * 3 + 2) // 2 % 45678)
s = int(input())
n = 1
while n * (n + 1) / 2 <= s:
n += 1
print(n - 1)
n_test = int(input())
for i in range(n_test):
t, n = map(int, input().split())
print(t, n + (n * (n + 1)) // 2)
N, M = map(int, input().split())
nums = list(map(int, input().split()))
accums = [0] * (N + 1)
for i in range(1, N + 1):
accums[i] = accums[i - 1] + nums[i - 1]
count = 0
for l in range(N):
for r in range(l + 1, N + 1):
if accums[r] - accums[l] > M:
break
elif accums[r] - accums[l] == M:
count += 1
break
print(count)
import sys
input = sys.stdin.readline
for _ in range(int(input())):
n = int(input())
score = sorted([tuple(map(int, input().split())) for _ in range(n)])
p, ans = n+1, 0
for s, e in score:
if p > e:
ans += 1
p = e
print(ans)
is_prime = [True for _ in range(4000001)]
for i in range(2, int(len(is_prime) ** 0.5)):
if is_prime[i]:
for j in range(i+i, len(is_prime), i):
is_prime[j] = False
primes = [i for i, j in enumerate(is_prime) if j == True and i >=2 ]
sum_prime = [0] * (len(primes) + 1)
for i in range(len(primes)):
sum_prime[i+1] = sum_prime[i] + primes[i]
N = int(input())
answer = 0
l, r = 0, 1
while l < len(primes):
if sum_prime[r] - sum_prime[l] == N:
answer += 1
l += 1
elif sum_prime[r] - sum_prime[l] < N and r < len(primes) - 1:
r += 1
else:
l += 1
print(answer)
class Solution:
def threeSum(self, nums: List[int]) -> List[List[int]]:
res = []
nums.sort()
for i in range(len(nums) - 2):
if i > 0 and nums[i] == nums[i-1]:
continue
l, r = i + 1, len(nums)-1
while l < r:
s = nums[i] + nums[l] + nums[r]
if s < 0:
l += 1
elif s > 0:
r -= 1
else:
res.append((nums[i], nums[l], nums[r]))
while l < r and nums[l] == nums[l+1]:
l += 1
while l < r and nums[r] == nums[r-1]:
r -= 1
l += 1; r -= 1
return res
# Greedy
N = int(input())
for i in range(0, N + 1, 3):
if (N - i) % 5 == 0:
print(i // 3 + (N - i) // 5)
break
else:
print(-1)
N = int(input())
for i in range(0, N + 1, 2):
if (N - i) % 5 == 0:
print(i // 2 + (N - i) // 5)
break
else:
print(-1)
N = int(input())
li = list(sorted([int(input()) for _ in range(N)], reverse=True))
ret = 0
for i, n in enumerate(li):
if (i + 1) * n > ret:
ret = (i + 1) *n
print(ret)
import sys
input = sys.stdin.readline
N = int(input())
discuss = [list(map(int, input().split())) for _ in range(N)]
cnt, time_now = 0, -1
for diss in sorted(discuss, key=lambda x: (x[1], x[0])):
if diss[0]>=time_now: #회의 시작 시간 >= 현재 시간
time_now = diss[1]
cnt+=1
print(cnt)
N, K = map(int, input().split())
li = [int(input()) for _ in range(N)]
ret = 0
for n in reversed(li):
ret += K // n
K %= n
print(ret)
N=int(input())
L = []
for i in range(N):
due, score = map(int,input().split())
L.append((score, due))
L.sort(reverse=True)
busy, total = set(), 0
for i in range(N):
score, due = L[i]
for j in range(due, 0, -1):
if j not in busy:
busy.add(j)
total += score
break
print(total)
BJ_14659 한조서열정리하고옴 (Bronze II)
N = int(input())
li = list(map(int, input().split()))
cur_height, cnt, mx = 0, 0, 0
for h in li:
if cur_height < h:
cur_height = h
cnt = 0
else:
cnt += 1
mx = max(cnt, mx)
print(mx)
n, m = map(int, input().split())
if n == 1:
print(1)
elif n == 2:
print(min(4, (m + 1) // 2))
elif m <= 6:
print(min(4, m))
else:
print(m - 2)
n=int(input())
a=[int(i) for i in input().split()]
b=[int(i) for i in input().split()]
c, r = 0, 0
for i in range(n-1):
if b[i]<b[c]:
c=i
r+=a[i]*b[c]
print(r)
S = input()
count = 0
for i in range(len(S)-1):
if S[i] != S[i+1]:
count += 1
print((count + 1) // 2)
n = int(input())
a = list(map(int, input().split()) )
b = []
for i in range(n):
b.insert(a[n-1-i], n - i)
print(*b)
equations = input().split('-')
ret = 0
for i, equation in enumerate(equations):
for num in equation.split('+'):
ret += int(num) if i == 0 else -int(num)
print(ret)
def change(A, B):
press = 0
for i in range(1, n):
if A[i-1] == B[i-1]:
continue
press += 1
for j in range(i-1, i+2):
if j < n:
A[j] ^= 1
return press if A == B else float('inf')
n = int(input())
A = list(map(int,input()))
B = list(map(int,input()))
f_A = A[:]
f_A[0] ^= 1
f_A[1] ^= 1
res = min(change(A, B), 1 + change(f_A, B))
print(res if res != float('inf') else -1)
N, M =map(int,input().split())
A = [list(map(int,list(input()))) for _ in range(N)]
B = [list(map(int,list(input()))) for _ in range(N)]
def flip(G, x,y):
for i in range(x,x+3):
for j in range(y,y+3):
G[i][j] = 1 - G[i][j]
cnt = 0
for i in range(0,N-2):
for j in range(0,M-2):
if A[i][j] !=B[i][j]:
flip(A, i,j)
cnt+=1
for i in range(N):
for j in range(M):
if A[i][j] != B[i][j]:
print(-1)
exit()
print(cnt)
from collections import Counter
input()
count = 0
height_cnt = Counter()
for h in map(int,input().split()):
if height_cnt[h] != 0:
height_cnt[h] -= 1
height_cnt[h - 1] += 1
else:
height_cnt[h - 1] += 1
print(sum(height_cnt.values()))
t = int(input())
ss = [input() for _ in range(t)]
alphabet = [0 for i in range(26)]
for s in ss:
i = 0
while s:
now = s[-1]
alphabet[ord(now) - ord('A')] += 10 ** i
i += 1
s = s[:-1]
alphabet.sort(reverse=True)
ans = 0
for i in range(9, 0, -1):
ans += i * alphabet[9 - i]
print(ans)
times = [(0, 600), (1320, 1440)]
for _ in range(int(input())):
a, b = input().split()
times.append((int(a[:2]) * 60 + int(a[2:]) - 10, int(b[:2]) * 60 + int(b[2:]) + 10))
times.sort()
mx, last_ended = 0, 600
for start, end in times:
mx = max(mx, start - last_ended)
last_ended = max(last_ended, end)
print(mx)
BJ_14790 Tidy Numbers (Bronze III)
BJ_14791 Tidy Numbers (Silver III)
def preceding_tidy(number):
number = list(map(int, number))
for i in range(len(number)-2, -1, -1):
if number[i] > number[i+1]:
number[i] -= 1
for j in range(i+1, len(number)):
number[j] = 9
return ''.join(str(n) for n in number).lstrip('0')
for i in range(int(input())):
print(f"Case #{i + 1}: {preceding_tidy(input())}")
import sys
input = sys.stdin.readline
n, m, b = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(n)]
height, ans = 0, float('inf')
for i in range(257):
mx, mn = 0, 0
for row in G:
for e in row:
if e < i:
mn += i - e
else:
mx += e - i
if mx + b >= mn:
time = 2 * mx + mn
if time <= ans:
ans = time
height = i
print(ans, height)
working_buttons = {str(x) for x in range(11)}
N = int(input())
n_broken = int(input())
if n_broken != 0:
working_buttons -= set(input().split())
result = abs(N - 100)
for i in range(1000001):
if len(set(str(i)) - working_buttons) == 0:
result = min(result, abs(N - i) + len(str(i)))
print(result)
n = int(input())
print('CY' if n % 2 == 0 else 'SK')
n = int(input())
print('CY' if n % 2 == 1 else 'SK')
n = int(input())
dp = [False, True, False, True, True]
for i in range(n - 4):
dp.append(not all([dp[-4], dp[-3], dp[-1]]))
print("SK" if dp[n] else "CY")
n = int(input())
dp = [True, False, True, False]
for i in range(n - 3):
dp.append(not all([dp[-4], dp[-3], dp[-1]]))
print("SK" if dp[n] else "CY")
print('SK' if int(input()) % 2 else 'CY')
print("CY" if int(input()) % 7 in [0, 2] else "SK")
print("CY" if int(input()) % 5 in [0, 2] else "SK")
n = int(input())
t = []
p = []
dp = []
for i in range(n):
a, b = map(int, input().split())
t.append(a)
p.append(b)
dp.append(b)
dp.append(0)
for i in range(n - 1, -1, -1):
if t[i] + i > n:
dp[i] = dp[i + 1]
else:
dp[i] = max(dp[i + 1], p[i] + dp[i + t[i]])
print(dp[0])
n = int(input())
li = [float(input()) for _ in range(n)]
dp = []
for n in li:
if len(dp) and dp[-1] > 1:
dp.append(dp[-1] * n)
else:
dp.append(n)
print(f"{max(dp):.3f}")
input()
li = list(map(int,input().split()))
dp = []
for n in li:
dp.append(dp[-1] + n if len(dp) and dp[-1] > 0 else n)
print(max(dp))
S1 = input()
S2 = input()
dp = [[0] * (len(S2) + 1) for _ in range(len(S1) + 1)]
for i, c1 in enumerate(S1):
for j, c2 in enumerate(S2):
if c1 == c2:
dp[i + 1][j + 1] = dp[i][j] + 1
else:
dp[i + 1][j + 1] = max(dp[i][j + 1], dp[i + 1][j])
print(dp[-1][-1])
S1 = input()
S2 = input()
dp = [[""] * (len(S2) + 1) for _ in range(len(S1) + 1)]
for i, c1 in enumerate(S1):
for j, c2 in enumerate(S2):
if c1 == c2:
dp[i + 1][j + 1] = dp[i][j] + c1
else:
if len(dp[i][j + 1]) > len(dp[i + 1][j]):
dp[i + 1][j + 1] = dp[i][j + 1]
else:
dp[i + 1][j + 1] = dp[i + 1][j]
print(len(dp[-1][-1]))
print(dp[-1][-1])
A, B, C = input(), input(), input()
dp = [[[0] * (len(C) + 1) for j in range(len(B) + 1)] for k in range(len(A) + 1)]
for i, a in enumerate(A):
for j, b in enumerate(B):
for k, c in enumerate(C):
if a == b == c:
dp[i + 1][j + 1][k + 1] = dp[i][j][k] + 1
else:
dp[i + 1][j + 1][k + 1] = max(dp[i][j + 1][k + 1], dp[i + 1][j][k + 1], dp[i + 1][j + 1][k], \
dp[i][j][k + 1], dp[i + 1][j][k], dp[i][j + 1][k])
print(dp[-1][-1][-1])
N, s = map(int, input().split())
li = list(map(int, input().split()))
acc = [0]
for n in li:
acc.append(acc[-1] + n)
mn_len = N
for i in range(N):
lo, hi = i, N - 1
if acc[hi + 1] - acc[i] < s:
break
while lo < hi:
mi = (lo + hi) // 2
if s <= acc[mi + 1] - acc[i]:
hi = mi
else:
lo = mi + 1
mn_len = min(mn_len, lo - i + 1)
print(0 if i == 0 else mn_len)
BJ_11054 가장 긴 바이토닉 부분 수열 (Gold III)
N = int(input())
li = list(map(int, input().split()))
increase = [1 for _ in range(N)]
decrease = [1 for _ in range(N)]
mx_bitonic = 1
for i in range(N):
for j in range(i):
if li[i] > li[j]:
increase[i] = max(increase[i], increase[j] + 1)
for i in range(N-1, -1, -1):
for j in range(i + 1, N):
if li[i] > li[j]:
decrease[i] = max(decrease[i], decrease[j] + 1)
mx_bitonic = max(mx_bitonic, decrease[i] + increase[i] - 1)
print(mx_bitonic)
n = int(input())
s = [list(map(int, input().split())) for i in range(n)]
dp = [[0] * n for i in range(n)]
for i in range(1, n):
for j in range(n - i):
x = j + i
dp[j][x] = 2 ** 32
for k in range(j, x):
dp[j][x] = min(dp[j][x], dp[j][k] + dp[k + 1][x] + s[j][0] * s[k][1] * s[x][1])
print(dp[0][-1])
n, m = map(int, input().split())
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
w, v = map(int, input().split())
for j in range(m + 1):
dp[i + 1][j] = max(dp[i][j], 0 if w > j else dp[i][j - w] + v)
print(dp[-1][-1])
N = int(input())
dp = [0, 1, 1]
for i in range(2, 102):
dp.append(dp[-1] + dp[-3])
for _ in range(N):
a = int(input())
print(dp[a])
dp = [0, 1]
for n in range(3, int(input()) + 1):
dp.append((n - 1) * (dp[-1] + dp[-2]) % 1000000000)
print(dp[-1])
n = int(input())
a, b = 1, 0
for i in range(2, n+1) :
a, b = b, ((i-1)*(a + b)) % 10**9
print(b)
n = int(input())
li = list(map(int, input().split()))
dp = [[-1] * (500001) for _ in range(n + 1)]
dp[0][0] = 0
for i, h in enumerate(li):
for d in range(500001):
dp[i + 1][d] = dp[i][d]
if d >= h and dp[i][d - h] != -1:
dp[i + 1][d] = max(dp[i + 1][d], dp[i][d - h] + h)
if h >= d and dp[i][h - d] != -1:
dp[i + 1][d] = max(dp[i + 1][d], dp[i][h - d] + d)
if d + h <= 500000 and dp[i][d + h] != -1:
dp[i + 1][d] = max(dp[i + 1][d], dp[i][d + h])
print(-1 if dp[n][0] == 0 else dp[n][0])
LC_121 best-time-to-buy-and-sell-stock
# row # transaction
# col day
vector<vector<int>> dp(k + 1, vector<int>(N));
for (int i = 1; i <= k; i++){
int mx = -v[0];
for (int j = 1; j < N; j++){
dp[i][j] = max(dp[i][j - 1], mx + v[j]);
mx = max(mx, dp[i - 1][j] - v[j]);
}
}
return dp[k][N - 1];
LC_312 Burst-balloons # burst gives nums[left] * nums[i] * nums[right] point
def maxCoins(self, li):
li = [1] + li + [1]
n = len(li)
dp = [[0] * n for _ in range(n)] # dp[i][j] coins obtained from balloons between index i and j
for gap in range(2, n):
for i in range(n - gap):
j = i + gap
for k in range(i+1, j): # k is last balloon index
dp[i][j] = max(dp[i][j], li[i] * li[k] * li[j] + dp[i][k] + dp[k][j])
return dp[0][n-1]
LC_10 regular-expression-matching
bool isMatch(string s, string p) {
int N = s.size(), M = p.size();
vector<vector<bool>> dp(N + 1, vector<bool>(M + 1, false));
dp[0][0] = true;
for (int j = 0; j < M; j++) {
if (p[j] == '*') {
dp[0][j + 1] = dp[0][j - 1];
}
}
for (int i = 0 ; i < N; i++) {
for (int j = 0; j < M; j++) {
if (p[j] == '.' || p[j] == s[i])
dp[i + 1][j + 1] = dp[i][j];
if (p[j] == '*') {
if (p[j - 1] == s[i] || p[j - 1] == '.')
dp[i + 1][j + 1] = dp[i + 1][j] || dp[i][j + 1]
|| dp[i + 1][j - 1];
else
dp[i + 1][j + 1] = dp[i + 1][j - 1];
}
}
}
return dp[N][M];
}
BJ_9095 1, 2, 3 더하기 (Silver III)
dp = [1, 1, 2]
for n in range(3, 11):
dp.append(dp[n-1] + dp[n-2] + dp[n-3])
for i in range(int(input())):
print(dp[int(input())])
BJ_12101 1, 2, 3 더하기 2 (Silver I)
n, k = map(int, input().split())
cnt = 0
def dfs(cur, total, string):
global cnt
if cur > total:
return
if cur == total:
cnt += 1
if cnt == k:
print(string[1:])
exit(0)
dfs(cur + 1, total, string + '+1')
dfs(cur + 2, total, string + '+2')
dfs(cur + 3, total, string + '+3')
dfs(0, n, '')
print(-1)
BJ_15988 1, 2, 3 더하기 3 (Silver II)
import sys
input = sys.stdin.readline
dp = [1, 1, 2]
for i in range(3, 1000001):
dp.append((dp[i - 1] + dp[i - 2] + dp[i - 3]) % 1000000009)
for i in range(int(input())):
n = int(input())
print(dp[n])
dp = [1, 1, 2]
for n in range(3, 1000001):
dp.append(dp[n-1] + dp[n-2] + dp[n-3])
for i in range(int(input())):
print(dp[int(input())] % 1000000009)
BJ_15989 1, 2, 3 더하기 4 (Silver I)
dp = [1 for i in range(10001)]
for i in range(2, 10001):
dp[i] += dp[i - 2]
for i in range(3, 10001):
dp[i] += dp[i - 3]
for _ in range(int(input())):
print(dp[int(input())])
N, total = map(int, input().split())
li = [int(input()) for _ in range(N)]
dp = [0] * (total + 1)
dp[0] = 1
for i in range(N):
coin = li[i]
for value in range(coin, total + 1):
dp[value] += dp[value - coin]
print(dp[-1])
N = int(input())
dp = [1] * 10
for i in range(N - 1):
for j in range(1, 10):
dp[j] += dp[j - 1]
print(dp)
print(sum(dp) % 10007)
N, K = map(int, input().split())
mod = 1000000000
table = [1] + [0] * N
for _ in range(1, K+1):
for i in range(1, N+1):
table[i] = (table[i] + table[i-1]) % mod
print(str(table[N]))
LC62_ Unique-paths # unique paths from TL to BR
def uniquePaths(self, m, n):
dp = [1] * n
for i in range(1, m):
for j in range(1, n):
dp[j] = dp[j - 1] + dp[j]
return dp[-1] if m and n else 0
Q. Given a target find minimum / maximum, cost / path / sum to reach the target
A. Choose min / max path among all possible paths before current state, then add value for current state
BJ_17626 Four Squares (Silver V)
n = int(input())
dp = [0] + [float('inf')] * n
for n in range(n + 1):
for root in range(int(n ** 0.5 + 1)):
dp[n] = min(dp[n], dp[n - root ** 2] + 1)
print(dp[-1])
n = int(input())
dp = [0]*(n+1)
for i in range(1, n+1):
dp[i] = i
j = 1
while j*j <= i:
if dp[i] > dp[i-j*j]+1:
dp[i] = dp[i-j*j]+1
j += 1
print(dp[n])
input()
li = list(map(int, input().split()))
dp = [0] + [1000] * (len(li) - 1)
for i in range(len(li)):
for step in range(1, li[i] + 1):
if i + step < len(dp):
dp[i + step] = min(dp[i + step], dp[i] + 1)
print(dp[-1] if dp[-1] < 1000 else -1)
n, m = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(n)]
dp = [[0] * (m + 1) for i in range(n + 1)]
for i in range(1, n + 1):
for j in range(1, m + 1):
dp[i][j] = G[i - 1][j - 1] + max(dp[i - 1][j], dp[i][j - 1], dp[i - 1][j - 1])
print(dp[n][m])
# find a path from top left to bottom right minimizes the sum
def minPathSum(self, grid):
r, c = len(grid), len(grid[0])
dp = [[0 for _ in range(c)] for _ in range(r)]
dp[0][0] = grid[0][0]
for i in range(1, r):
dp[i][0] = dp[i-1][0] + grid[i][0]
for i in range(1, c):
dp[0][i] = dp[0][i-1] + grid[0][i]
for i in range(1, r):
for j in range(1, c):
dp[i][j] = min(dp[i-1][j], dp[i][j-1]) + grid[i][j]
return dp[-1][-1]
# largest square containing only 1's
def maximalSquare(self, G):
if len(G) == 0:
return 0
n, m, ret, flag = len(G), len(G[0]), 0, 0
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
for j in range(m):
if G[i][j] == '1':
dp[i + 1][j + 1] = min(dp[i + 1][j], dp[i][j], dp[i][j + 1]) + 1
ret = max(ret, dp[i + 1][j + 1])
return ret ** 2
# with flag
for i in range(n):
for j in range(m):
if G[i][j] == '1':
dp[flag][j + 1] = min(dp[flag][j], dp[flag ^ 1][j], dp[flag ^ 1][j + 1]) + 1
ret = max(ret, dp[flag][j + 1])
else:
dp[flag][j + 1] = 0
flag ^= 1
P = input()
def getPi(st):
j = 0
pi = [0] * len(st)
for i in range(1, len(pi)):
while j > 0 and st[i] != st[j]:
j = pi[j-1]
if st[i] == st[j]:
j += 1
pi[i] = j
return max(pi)
res = 0
for i in range(len(P)):
res = max(getPi(P[i:]), res)
print(res)
Knapsack problem w[1], ..., w[n] and values v[1], ..., v[n] given that you cannot have more weight than C.
n, m = map(int, input().split())
dp = [[0] * (m + 1) for _ in range(n + 1)]
for i in range(n):
w, v = map(int, input().split())
for j in range(m + 1):
dp[i + 1][j] = max(dp[i][j], 0 if w > j else dp[i][j - w] + v)
print(dp[-1][-1])
// row current vertex
// col visited bitset
const int N = 20, INF = 100000000;
int c[N][N];
int dp[N][1<<N];
memset(dp, -1, sizeof(dp));
int tsp(int i, int S) {
if (S == ((1 << N) - 1))
return c[i][0];
if (dp[i][S] != -1)
return dp[i][S];
int res = INF;
for (int j = 0; j < N; j++) {
if (S & (1 << j))
continue;
res = min(res, c[i][j] + tsp(j, S | (1 << j)));
}
dp[i][S] = res;
return res;
}
INF=float('inf')
def find_path(last, visited, dp):
if visited == (1<<N) - 1:
return G[last][0] or INF
if dp[last][visited] is not None:
return dp[last][visited]
tmp=INF
for city in range(N):
if visited & (1 << city) == 0 and G[last][city] != 0:
tmp=min(tmp, find_path(city, visited | (1<<city), dp) + G[last][city])
dp[last][visited]=tmp
return tmp
N=int(input())
G=[list(map(int,input().split())) for _ in range(N]
dp = [[None]*(1<<N) for _ in range(N)] # dp[a][b] = current node a, visited nodes bit
print(find_path(0, 1, dp))
Brute Force # Memory O(1) Time O(N)
Dynamic Program # Memory O(N^2) Time O(1)
Segment Tree # Memory O(N) Time O(log N)
Sparse Table # Memory O(NlogN) Time O(1)
LCA # Memory O(N) Time O(1)
import sys
input = sys.stdin.readline
m=int(input())
f=[0]+list(map(int, input().split()))
dp=[[f[i]] for i in range(m+1)]
for exp in range(19): # log(20000) < 19
for i in range(1,m+1):
dp[i].append(dp[dp[i][exp]][exp])
for _ in range(int(input())):
n, x = map(int, input().split())
for exp in range(18, -1, -1):
if n >= 2 ** exp:
n -= 2 ** exp
x = dp[x][exp]
print(x)
import sys
from collections import deque
input = sys.stdin.readline
N=int(input())
T=[[] for _ in range(N+1)]
for _ in range(N-1):
p,c = map(int,input().split())
T[c].append(p)
T[p].append(c)
node2parent=[0 for _ in range(N+1)]
node2depth= {1:0}
dq=deque([1])
while dq:
p = dq.popleft()
for c in T[p]:
if c not in node2depth:
node2parent[c] = p
dq.append(c)
node2depth[c] = node2depth[p] + 1
dp=[[0 for _ in range(17)] for i in range(N+1)]
for i in range(N+1):
dp[i][0]=node2parent[i]
for j in range(1,17):
for i in range(1,N+1):
dp[i][j]=dp[dp[i][j-1]][j-1]
for _ in range(int(input())):
a, b = map(int, input().split())
if node2depth[a] > node2depth[b]:
a, b = b, a
dif = node2depth[b] - node2depth[a]
for i in range(17):
if dif & 1<<i:
b=dp[b][i]
if a == b:
print(a)
continue
for i in range(16,-1,-1):
if dp[a][i] != dp[b][i]:
a=dp[a][i]
b=dp[b][i]
print(dp[b][0])
Comparing Iterative and Recursive Factorial Functions
Stepping Through Recursive Fibonacci Function
def recur(n):
if n <= 1: return n
return recur(n - 1) + recur(n - 2)
print(recur(int(input())))
BJ_17478 재귀함수가 뭔가요? (Silver V)
def recur(mx, cur):
if cur == mx:
print("____" * cur + '"재귀함수가 뭔가요?"')
print("____" * cur + '"재귀함수는 자기 자신을 호출하는 함수라네"')
print("____" * cur + '라고 답변하였지.')
return
print("____" * cur + '"재귀함수가 뭔가요?"')
print("____" * cur + '"잘 들어보게. 옛날옛날 한 산 꼭대기에 이세상 모든 지식을 통달한 선인이 있었어.')
print("____" * cur + '마을 사람들은 모두 그 선인에게 수많은 질문을 했고, 모두 지혜롭게 대답해 주었지.')
print("____" * cur + '그의 답은 대부분 옳았다고 하네. 그런데 어느 날, 그 선인에게 한 선비가 찾아와서 물었어."')
recur(mx, cur + 1)
print("____" * cur + '라고 답변하였지.')
print("어느 한 컴퓨터공학과 학생이 유명한 교수님을 찾아가 물었다.")
n = int(input())
recur(n, 0)
def recur(r, c, n):
global G, blue, white
total = sum(sum(li[c : c + n]) for li in G[r : r + n])
if total == 0:
white +=1
elif total == n ** 2:
blue += 1
else:
recur(r, c, n // 2)
recur(r + n // 2, c, n // 2)
recur(r, c + n // 2, n // 2)
recur(r + n // 2, c + n // 2, n // 2)
G = []
n = int(input())
for _ in range(n):
G.append(list(map(int, input().split())))
blue = 0
white = 0
recur(0, 0, len(G))
print(white)
print(blue)
import sys
sys.setrecursionlimit(10**6)
input = sys.stdin.readline
def same(x, y, n):
for i in range(x, x+n):
for j in range(y, y+n):
if G[x][y] != G[i][j]:
return False
return True
def solve(x, y, n):
if same(x, y, n):
cnt[G[x][y]+1] += 1
return
for i in range(0, 3):
for j in range(0, 3):
solve(x + i * n // 3, y + j * n // 3, n // 3)
cnt = [0] * 3
n = int(input())
G = [list(map(int, input().split())) for _ in range(n)]
solve(0, 0, n)
for i in cnt:
print(i)
BJ_11729 하노이 탑 이동 순서 (Silver II)
def hanoi(disk, start, mid, end):
if disk == 1:
moves.append([start, end])
else:
hanoi(disk - 1, start, end, mid)
moves.append([start, end])
hanoi(disk - 1, mid, start, end)
total_disk = int(input())
moves = []
hanoi(total_disk, 1, 2, 3)
print(len(moves))
for move in moves:
print(move[0], move[1])
def recur(N, r, c):
if r == c == 0:
return 0
side = 2 ** (N - 1)
return recur(N - 1, r % side, c % side) + side ** 2 * (r // side * 2 + c // side)
N, r, c = map(int, input().split())
print(recur(N, r, c))
def recur(old_G):
new_G=[]
for i in range(3 * len(old_G)):
if i // len(old_G) == 1:
new_G.append(old_G[i % len(old_G)] + " " * len(old_G) + old_G[i % len(old_G)])
else:
new_G.append(old_G[i % len(old_G)] * 3)
return new_G
G = ["*"]
i = 1
N = int(input())
while i != N:
G = recur(G)
i *= 3
for i in G:
print(i)
A, B, C = map(int, input().split())
def recur(A, B):
if(B % 2 > 0):
return recur(A, B - 1) * A
elif(B == 0):
return 1
elif(B == 1):
return A
else:
result = recur(A, B//2)
return result ** 2 % C
print(recur(A, B) % C)
BJ_12100 2048 (Easy) (Gold II)
from copy import deepcopy
def move(G, typ):
result = []
if typ == 0 or typ == 1:
G = list(zip(*G))
for idx in range(len(G)):
row = G[idx]
block = [i for i in row if i != 0]
if typ == 0 or typ == 3:
for i in range(1, len(block)):
if block[i-1] == block[i]:
block[i-1] += block[i]
block[i] = 0
block = [i for i in block if i != 0]
block += [0] * (len(row) - len(block))
else:
for i in range(len(block) - 1, 0, -1):
if block[i-1] == block[i]:
block[i] += block[i-1]
block[i-1] = 0
block = [i for i in block if i != 0]
block = [0] * (len(row) - len(block)) + block
result.append(block)
if typ == 0 or typ == 1:
result = list(zip(*result))
return result
def recur(G, count):
if count == 0:
return max([max(li) for li in G])
return max([recur(move(deepcopy(G), typ), count - 1) for typ in range(4)])
n = int(input())
G = [list(map(int, input().split())) for _ in range(n)]
print(recur(G, 5))
Bounding function : kill some live nodes without actually expanding them
BJ_15649 N과 M (1) (Silver III)
N, M = map(int, input().split())
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(1, N + 1):
if i not in cur:
cur.append(i)
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15650 N과 M (2) (Silver III)
N, M = map(int, input().split())
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(cur[-1] + 1 if cur else 1, N + 1):
cur.append(i)
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15651 N과 M (3) (Silver III)
N, M = map(int, input().split())
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(1, N + 1):
cur.append(i)
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15652 N과 M (4) (Silver III)
N, M = map(int, input().split())
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(cur[-1] if cur else 1, N + 1):
cur.append(i)
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15654 N과 M (5) (Silver III)
N, M = map(int, input().split())
li=list(sorted(map(int, input().split())))
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(N):
if not cur or li[i] != cur[-1]:
cur.append(li[i])
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15654 N과 M (6) (Silver III)
N, M = map(int, input().split())
li=list(sorted(map(int, input().split())))
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(N):
if not cur or li[i] > cur[-1]:
cur.append(li[i])
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15656 N과 M (7) (Silver III)
N, M = map(int, input().split())
li=list(sorted(map(int, input().split())))
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(N):
cur.append(li[i])
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
BJ_15657 N과 M (8) (Silver III)
N, M = map(int, input().split())
li=list(sorted(map(int, input().split())))
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(N):
if not cur or li[i] >= cur[-1]:
cur.append(li[i])
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
N, M = map(int, input().split())
li = list(sorted(map(int, input().split())))
def backtrack(cur, N, M):
if len(cur) == M:
print(*cur)
return
for i in range(N):
if (not cur or cur[-1] != li[i]) and li[i] != li[i - 1]:
cur.append(li[i])
backtrack(cur, N, M)
cur.pop()
backtrack([], N, M)
def solve(ops, cur, results):
idx = len(cur)
if idx == len(ops) + 1:
if len(results) <= 1:
results.append(cur)
results[-1] = cur
return
for i in range(10):
if not c[i]:
if idx == 0 or ops[idx - 1] == '<' and cur[-1] < str(i) or ops[idx - 1] == '>' and cur[-1] > str(i):
c[i] = True
solve(ops, cur + str(i), results)
c[i] = False
n = int(input())
ops = input().split()
c = [False] * 10
results = []
solve(ops, "", results)
print(results[1], results[0], sep='\n')
N=int(input())
def backtrack(mx, c = 0, row=None, left=None, right=None):
count = 0
if c == 0:
row, left, right = [0] * mx, [0] * 2 * mx, [0] * 2 * mx
if c == mx:
return 1
for r in range(mx):
if row[r] + left[c+r] + right[mx - 1 + c - r]==0:
row[r] = left[c+r] = right[mx - 1 + c - r] = 1
count += backtrack(mx, c + 1, row, left, right)
row[r] = left[c + r] = right[mx - 1 + c - r] = 0
return count
print(backtrack(N))
"""
Instance : a partially filled in puzzle.
Solution format : a grid with all squares filled with the numbers 1 through 9.
Constraint : There can be no repeats of numbers in each sub-square, row or column.
Objective : Find a solution with the constraint.
Fill the first available cell with the least possible number and recurse until any cell can't be filled in.
Go back to the last decision point and try the next biggest possible number.
"""
def backtrack(G):
for r in range(9):
for c, v in enumerate(G[r]):
if v != 0: continue
box = [G[r//3*3+i][c//3*3+j] for i in range(3) for j in range(3)]
row_col = G[r] + [G[i][c] for i in range(9)]
for n in set(range(1, 10)) - set(box + row_col):
G[r][c] = n
if backtrack(G):
break
else:
G[r][c] = 0
else:
return False
return True
G = [list(map(int, input().split())) for _ in range(9)]
backtrack(G)
for l in G:
for n in l:
print(n, end = ' ')
print()
https://www.acmicpc.net/problem/15655
https://www.acmicpc.net/problem/15656
https://www.acmicpc.net/problem/15657
https://www.acmicpc.net/problem/15663
# unique combinations in candidates where the candidate numbers sums to target
vector<vector<int>> combinationSum(vector<int> &v, int target) {
vector<vector<int>> ret;
sort(v.begin(), v.end());
bt(v, 0, target, vector<int>(), ret);
return ret;
}
void bt(vector<int>& v, int index, int target, vector<int> cur, vector<vector<int>>& ret) {
if (target == 0) {
ret.push_back(cur);
return;
}
for (int i = index; i < v.size() && v[i] <= target; i++) {
if (i == index || v[i] != v[i - 1]) {
cur.push_back(v[i]);
bt(v, i + 1, target - v[i], cur, ret);
cur.pop_back();
}
}
}
# adjacency matrix
# dict of dict {'a': {'b': -1, 'c': 4}, 'b': {'c': 3}, ...}
import sys
sys.setrecursionlimit(1500)
def dfs(G, w, h):
if 0 <= w < len(G) and 0 <= h < len(G[0]) and G[w][h] == 1:
G[w][h] = -1
for i, j in [(1, 1), (1, 0), (1, -1), (0, 1), (0, -1), (-1, 0), (-1, 1), (-1, 0), (-1, -1)]:
dfs(G, w + i, h + j)
while True:
first_line = input()
if first_line == "0 0":
break
w, h = map(int, first_line.split())
G = []
for i in range(h):
G.append(list(map(int, input().split())))
count = 0
for r in range(h):
for c in range(w):
if G[r][c] == 1:
count += 1
dfs(G, r, c)
print(count)
BJ_11724 연결 요소의 개수 (Silver II)
import sys
sys.setrecursionlimit(10000)
def dfs(G, start, visited=None):
visited.add(start)
for adj in G[start]:
if adj not in visited:
dfs(G, adj, visited)
N, M = map(int, input().split())
G = [[] for _ in range(N + 1)]
count = 0
for _ in range(M):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
visited = set()
for j in range(1, N + 1):
if j not in visited:
dfs(G, j, visited)
count += 1
print(count)
for _ in range(int(input())):
n = int(input())
choice = list(n - 1 for n in map(int, input().split()))
visit = [0] * n
group = 1
for i in range(n):
while visit[i] == 0:
visit[i] = group
i = choice[i]
while visit[i] == group:
visit[i] = -1
i = choice[i]
group += 1
print(n - visit.count(-1))
from collections import defaultdict
while True:
N = int(input())
if N == -1:
break
G = defaultdict(set)
for i in range(N):
for j, e in enumerate(list(map(int, input().split()))):
if e == 1:
G[i].add(j)
for i in range(N):
count = 0
for j in G[i]:
count += sum([1 for k in G[j] if k in G[i]])
if count == 0:
print(i, end = ' ')
print()
import sys
sys.setrecursionlimit(1500)
def dfs(G, r, c, dp):
if dp[r][c] != -1:
return dp[r][c]
dp[r][c] = 0
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G[0]):
if G[nr][nc] < G[r][c]:
dp[r][c] += dfs(G, nr, nc, dp)
return dp[r][c]
m, n = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(m)]
dp = [[-1]*n for _ in range(m)]
dp[-1][-1] = 1
print(dfs(G, 0, 0, dp))
import sys
input = sys.stdin.readline
T = int(input())
for _ in range(T):
N, M = map(int, input().split())
for _ in range(M):
a, b = map(int, input().split())
print(N - 1)
from collections import deque
def bfs(G, start):
dq, visited = deque([start]), set()
while len(dq) != 0:
v = dq.popleft()
if v not in visited:
visited.add(v)
dq.extend(sorted(set(G[v]) - visited))
return len(visited)
N, M = int(input()), int(input())
G = [[] for _ in range(N)]
for _ in range(M):
u, v = map(int, input().split())
G[u - 1].append(v - 1)
G[v - 1].append(u - 1)
print(bfs(G, 0) - 1)
from collections import deque
def dfs(G, v, visited=None):
visited = visited or set([v])
print(v, end=' ')
for neighbor in sorted(G[v]):
if neighbor not in visited:
visited.add(neighbor)
dfs(G, neighbor, visited)
return visited
def bfs(G, start):
dq, visited = deque([start]), set()
while len(dq) != 0:
v = dq.popleft()
if v not in visited:
print(v, end=' ')
visited.add(v)
dq.extend(sorted(set(G[v]) - visited))
N, M, v = map(int, input().split())
G = [[] for i in range(N+1)]
for i in range(M):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
dfs(G, v)
print()
bfs(G, v)
from collections import deque
def bfs(G, start):
dq, visited = deque([start]), set([start])
for _ in range(2):
for _ in range(len(dq)):
v = dq.popleft()
for e in G[v]:
if e not in visited:
dq.append(e)
visited.add(e)
return len(visited) - 1
V, E = int(input()), int(input())
G = [[] for _ in range(V + 1)]
for _ in range(E):
u, v = map(int, input().split())
G[u].append(v)
G[v].append(u)
print(bfs(G, 1))
from itertools import chain
from collections import deque
def bfs(G, rottens):
dq = deque(rottens)
while dq:
for _ in range(len(dq)):
r, c = dq.popleft()
for nr, nc in [(r + 1, c),(r, c + 1),(r - 1, c),(r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] == 0:
G[nr][nc] = G[r][c] + 1
dq.append([nr, nc])
return -1 if 0 in chain(*G) else max(chain(*G)) - 1
M, N = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(N)]
rottens = []
for i in range(N):
for j in range(M):
if G[i][j] == 1:
rottens.append((i, j))
print(bfs(G, rottens))
import collections
def bfs(G, r, c):
q = collections.deque([(r, c)])
while q:
r, c = q.popleft()
for nr, nc in [(r,c-1),(r,c+1),(r-1,c),(r+1,c)]:
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] == 1:
q.append((nr, nc))
G[nr][nc] = G[r][c] + 1
return G[-1][-1]
N, M = map(int,input().split())
G = [list(map(int,input())) for _ in range(N)]
print(bfs(G, 0,0))
from collections import deque
def bfs(start, end):
dq, node2dist = deque([start]), {start : 0}
while len(dq) != 0:
v = dq.popleft()
if v == end:
return node2dist[end]
for adj in [v + 1, v - 1, v * 2]:
if adj not in node2dist and adj <= 100000:
node2dist[adj] = node2dist[v] + 1
dq.append(adj)
start, end = map(int, input().split())
print(bfs(start, end))
from collections import deque
from copy import deepcopy
def floodfill(G, r, c, colors):
dq, visited = deque([(r, c)]), set([(r, c)])
G[r][c] = '_'
while len(dq) != 0:
r, c = dq.popleft()
for nr, nc in ([r, c + 1], [r, c - 1], [r + 1, c], [r - 1, c]):
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] in colors:
G[nr][nc] = '_'
visited.add((nr, nc))
dq.append((nr, nc))
return len(visited)
from copy import deepcopy
import collections
def bfs(G):
dq, air = collections.deque([(0, 0)]), set([(0, 0)])
while dq:
r, c = dq.popleft()
for nr, nc in [(r,c-1),(r,c+1),(r-1,c),(r+1,c)]:
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] == 0 and (nr, nc) not in air:
dq.append((nr, nc))
air.add((nr, nc))
return air
N, M = map(int, input().split())
G = [[0] * (M + 2)] + [[0] + list(map(int, input().split())) + [0] for _ in range(N)] + [[0] * (M + 2)]
cheeses = set([(r, c) for r in range(N + 2) for c in range(M + 2) if G[r][c] == 1])
count = 0
while len(cheeses):
count += 1
n_cheese = len(cheeses)
air = bfs(G)
for r, c in deepcopy(cheeses):
if {(r + 1, c), (r - 1, c), (r, c - 1), (r, c + 1)} & air:
G[r][c] = 0
cheeses.remove((r, c))
print(count)
print(n_cheese)
N = int(input())
G = [list(input()) for _ in range(N)]
cb_G = deepcopy(G)
count = 0
for r in range(N):
for c in range(N):
if G[r][c] != '_':
floodfill(G, r, c, G[r][c])
count += 1
print(count, end=' ')
cb_count = 0
for r in range(N):
for c in range(N):
if cb_G[r][c] != '_':
floodfill(cb_G, r, c, 'RG' if cb_G[r][c] != 'B' else 'B')
cb_count += 1
print(cb_count)
from collections import deque
def bfs(start, end):
dq, node2dist = deque([start]), {start:0}
while dq:
v = dq.popleft()
if v == end:
return node2dist[v]
for adj in (v - 1, v + 1, 2 * v):
if adj not in node2dist and adj <= 100000:
if adj == 2 * v:
node2dist[adj] = node2dist[v]
dq.appendleft(adj)
else:
node2dist[adj] = node2dist[v] + 1
dq.append(adj)
start, end = map(int, input().split())
print(bfs(start, end))
from collections import deque
def bfs(start, end):
dq, node2dist, node2head = deque([start]), {start : 0}, {}
while len(dq) != 0:
v = dq.popleft()
for adj in [v + 1, v - 1, v * 2]:
if adj not in node2dist and adj <= 100000:
node2head[adj] = v
node2dist[adj] = node2dist[v] + 0 if adj == v * 2 else 1
dq.append(adj)
if v == end:
return node2head
start, end = map(int, input().split())
path = [end]
cur = end
node2head = bfs(start, end)
while cur != start:
cur = node2head[cur]
path.append(cur)
print(len(path) - 1)
print(*reversed(path))
import copy
from collections import deque
from itertools import combinations, chain
def bfs(G, r, c):
dq = deque()
for r in range(len(G)):
for c in range(len(G[0])):
if G[r][c] == 2:
dq.append((r, c))
while dq:
r, c = dq.popleft()
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < n and 0 <= nc < m:
if G[nr][nc] == 0:
G[nr][nc] = 2
dq.append((nr, nc))
return list(chain(*G)).count(0)
n, m = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(n)]
blanks = []
for r in range(n):
for c in range(m):
if G[r][c] == 0:
blanks.append((r, c))
ret = 0
for walls in combinations(blanks, 3):
new_G = copy.deepcopy(G)
for r, c in walls:
new_G[r][c] = 1
ret = max(ret, bfs(new_G, r, c))
print(ret)
from copy import deepcopy
from collections import deque
from itertools import combinations
def bfs(G, virs):
visited, dq = set(virs), deque([(*vir, 0) for vir in virs])
last_change = 0
while dq:
r, c, cnt = dq.popleft()
G[r][c] = 1
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G) and (nr, nc) not in visited and G[nr][nc] != 1:
visited.add((nr, nc))
last_change = cnt + 1
dq.append((nr, nc, cnt + 1))
return last_change if sum([li.count(1) for li in G]) == len(G) ** 2 else float('inf')
n, m = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(n)]
virs = [(r, c) for r in range(n) for c in range(n) if G[r][c] == 2]
result = float('inf')
for selects in combinations(virs, m):
result = min(result, bfs(deepcopy(G), selects))
print(-1 if result == float('inf') else result)
from copy import deepcopy
from collections import deque
from itertools import combinations
def bfs(G, virs):
visited, dq = set(), deque([(*vir, 0) for vir in virs])
last_change = 0
while dq:
r, c, cnt = dq.popleft()
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G) and (nr, nc) not in visited and G[nr][nc] != 1:
visited.add((nr, nc))
if G[nr][nc] == 0:
G[nr][nc] = 2
last_change = cnt + 1
dq.append((nr, nc, cnt + 1))
return last_change if sum([li.count(0) for li in G]) == 0 else -1
n, m = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(n)]
virs = [(r, c) for r in range(n) for c in range(n) if G[r][c] == 2]
result = float('inf')
for selects in combinations(virs, m):
cur = bfs(deepcopy(G), selects)
if cur != -1:
result = min(result, cur)
print(-1 if result == float('inf') else result)
def BFS(G, x, y):
answer = 1
q = set([(x, y, G[x][y])])
while q:
x, y, ans = q.pop()
for nr, nc in [(x + 1, y), (x, y + 1), (x - 1, y), (x, y - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] not in ans:
q.add((nr,nc,ans + G[nr][nc]))
answer = max(answer, len(ans) + 1)
return answer
R, C = map(int, input().split())
G = [input() for _ in range(R)]
return(BFS(G, 0, 0))
from collections import deque, defaultdict
def bfs(G, start, end, carry):
dq = deque([start])
visited = [i == start for i in range(len(G))]
while dq:
u = dq.popleft()
for adj, limit in G[u].items():
if not visited[adj] and carry <= limit:
dq.append(adj)
visited[adj] = True
return visited[end]
n, m = map(int, input().split())
G = [defaultdict(int) for _ in range(n)]
for _ in range(m):
u, v, w = map(int, input().split())
G[u - 1][v - 1] = max(G[u - 1][v - 1], w)
G[v - 1][u - 1] = max(G[v - 1][u - 1], w)
start, end = map(int, input().split())
start -= 1; end -= 1
lo_w = 1
hi_w = 1000000000
while lo_w < hi_w:
mi_w = (hi_w + lo_w + 1) // 2
if bfs(G, start, end, mi_w):
lo_w = mi_w
else:
hi_w = mi_w - 1
print(lo_w)
from collections import deque
def floodfill(G, r, c):
dq = deque([(r, c)])
G[r][c] = 0
while len(dq) != 0:
r, c = dq.popleft()
for nr, nc in ([r, c + 1], [r, c - 1], [r + 1, c], [r - 1, c]):
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] == 1:
G[nr][nc] = 0
dq.append((nr, nc))
n_test = int(input())
for _ in range(n_test):
N, M, E = map(int, input().split())
G = [[0] * M for _ in range(N)]
for _ in range(E):
r, c = map(int, input().split())
G[r][c] = 1
count = 0
for i in range(N):
for j in range(M):
if G[i][j]:
floodfill(G, i, j)
count += 1
print(count)
from collections import deque
def floodfill(G, r, c):
dq, visited = deque([(r, c)]), set([(r, c)])
G[r][c] = 0
while len(dq) != 0:
r, c = dq.popleft()
for nr, nc in ([r, c + 1], [r, c - 1], [r + 1, c], [r - 1, c]):
if 0 <= nr < len(G) and 0 <= nc < len(G[0]) and G[nr][nc] == 1:
G[nr][nc] = 0
visited.add((nr, nc))
dq.append((nr, nc))
return len(visited)
N, M = map(int, input().split())
G = [list(map(int, input().split())) for _ in range(N)]
mx_size, count = 0, 0
for i in range(N):
for j in range(M):
if G[i][j] == 1:
count += 1
mx_size = max(mx_size, floodfill(G, i, j))
print(count)
print(mx_size)
import sys
from collections import deque
input = sys.stdin.readline
def floodfill(G, i, j, gid):
q = deque([(i, j)])
G[i][j] = gid
while q:
r, c = q.popleft()
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G) and G[nr][nc] == 1:
G[nr][nc] = gid
q.append((nr, nc))
def get_distance(G):
loop = 0
dq = deque([(r, c) for r in range(len(G)) for c in range(len(G)) if G[r][c] != 0])
while dq:
loop += 1
for _ in range(len(dq)):
r, c = dq.popleft()
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G):
if G[nr][nc] == 0:
G[nr][nc] = G[r][c]
dq.append((nr, nc))
elif G[nr][nc] < G[r][c]:
return loop * 2 - 2
elif G[nr][nc] > G[r][c]:
return loop * 2 - 1
n = int(input())
G = [list(map(int, input().split())) for _ in range(n)]
gid = -1
for i in range(len(G)):
for j in range(len(G)):
if G[i][j] > 0:
floodfill(G, i, j, gid)
gid -= 1
print(get_distance(G))
from collections import deque
def bfs(G, r, c):
dq = deque([[0, 0, 1]])
dp = [[[0] * 2 for i in range(m)] for i in range(n)]
dp[r][c][1] = 1
while dq:
a, b, w = dq.popleft()
if a == n - 1 and b == m - 1:
return dp[a][b][w]
for r, c in [(a + 1, b), (a, b + 1), (a - 1, b), (a, b - 1)]:
if 0 <= r < n and 0 <= c < m:
if G[r][c] == '1' and w == 1:
dp[r][c][0] = dp[a][b][1] + 1
dq.append([r, c, 0])
elif G[r][c] == '0' and dp[r][c][w] == 0:
dp[r][c][w] = dp[a][b][w] + 1
dq.append([r, c, w])
return -1
n, m = map(int, input().split())
G = [input() for _ in range(n)]
print(bfs(G, 0, 0))
BJ_11725 트리의 부모 찾기 (Silver II)
import sys
sys.setrecursionlimit(10**9)
def dfs(G, start, node2head):
for adj in sorted(G[start]):
if adj not in node2head:
node2head[adj] = start
dfs(G, adj, node2head)
N = int(input())
G = [[] for i in range(N+1)]
for _ in range(N - 1):
a, b = map(int, input().split())
G[a].append(b)
G[b].append(a)
node2head = {1 : 0}
dfs(G, 1, node2head)
for i in range(2, N + 1):
print(node2head[i])
def dfs(v):
if len(G[v]) == 0:
return 1
else:
return sum(dfs(child) for child in G[v])
n = int(input())
G = [[] for _ in range(52)]
li = list(map(int,input().split()))
t = int(input())
for v, parent in enumerate(li):
if parent == -1:
start = v
elif v != t:
G[parent].append(v)
if start != t:
print(dfs(start))
else :
print(0)
# traversal
# inorder left, root, right
# preorder root, left, right
# postorder left, right, root
import sys
sys.setrecursionlimit(1000000)
n = int(input())
data2node = dict()
class Node:
def __init__(self, data, left = None, right = None):
self.data = data
self.left = left
self.right = right
def dfs(node, debug):
if not node:
return
if debug == "pre":
print(node.data, end='')
if node.left:
dfs(data2node[node.left.data], debug)
if debug == "in":
print(node.data, end='')
if node.right:
dfs(data2node[node.right.data], debug)
if debug == "post":
print(node.data, end='')
for i in range(n):
a, b, c = input().split()
if b != '.':
data2node[b] = Node(b)
if c!= '.':
data2node[c] = Node(c)
data2node[a] = Node(a, data2node.get(b), data2node.get(c))
for order in ["pre", "in", "post"]:
dfs(data2node['A'], order)
print()
import sys
input = sys.stdin.readline
def dfs(G, v, result):
for e, d in G[v]:
if result[e] == 0:
result[e] = result[v] + d
dfs(G, e, result)
N = int(input())
G = [[] for _ in range(N + 1)]
for _ in range(N):
path = list(map(int, input().split()))
for i in range(1, len(path) - 2, 2):
G[path[0]].append([path[i], path[i + 1]])
root2dist = [0 for _ in range(N + 1)]
dfs(G, 1, root2dist)
root2dist[1]=0
index = root2dist.index(max(root2dist))
leaf2dist = [0 for _ in range(N + 1)]
dfs(G, index, leaf2dist)
leaf2dist[index] = 0
print(max(leaf2dist))
import sys
from collections import deque
input = sys.stdin.readline
def bfs(G, x):
dq = deque([x])
dist = [-1 for _ in range(n)]
dist[x] = 0
while dq:
x = dq.popleft()
for w, nx in G[x]:
if dist[nx] == -1:
dist[nx] = dist[x] + w
dq.append(nx)
return max(dist), dist.index(max(dist))
n = int(input())
G = [[] for _ in range(n)]
for i in range(n-1):
x, y, w = map(int, input().split())
G[x-1].append([w, y-1])
G[y-1].append([w, x-1])
print(bfs(G, bfs(G, 0)[1])[0])
BJ_2533 사회망 서비스(SNS) (Gold II)
import sys
input = sys.stdin.readline
sys.setrecursionlimit(10**9)
def dfs(cur, visited):
visited.add(cur)
dp[cur][0]=1
dp[cur][1]=0
for adj in G[cur]:
if adj not in visited:
dfs(adj, visited)
dp[cur][0]+=dp[adj][1]
dp[cur][1]+=max(dp[adj][0],dp[adj][1])
N=int(input())
G=[[] for _ in range(N)]
for _ in range(N-1):
u,v=map(int,input().split())
G[u - 1].append(v - 1)
G[v - 1].append(u - 1)
dp=[[0,0] for _ in range(N)] # contain / not
dfs(0, set())
print(dp)
print(N-max(dp[0][0], dp[0][1]))
from heapq import heappush, heappop
def dijkstra(G, start):
dp = [0 if v == start else float('inf') for v in range(len(G))]
heap = [(0, start)]
while heap:
w, n = heappop(heap)
for n_n, wei in G[n]:
n_w = wei + w
if n_w < dp[n_n]:
dp[n_n] = n_w
heappush(heap, [n_w, n_n])
return dp
V, E = int(input()), int(input())
G = [[] for _ in range(V)]
for _ in range(E):
u, v, w = map(int, input().split())
G[u - 1].append((v - 1, w))
start, end = map(int, input().split())
print(dijkstra(G, start - 1)[end - 1])
from heapq import heappush, heappop
def dijkstra(G, start):
dp = [0 if v == start else float('inf') for v in range(len(G))]
heap = [(0, start)]
while heap:
w, n = heappop(heap)
for n_n, wei in G[n]:
n_w = wei + w
if n_w < dp[n_n]:
dp[n_n] = n_w
heappush(heap, [n_w, n_n])
return dp
v, e = map(int, input().split())
k = int(input())
G = [[] for _ in range(v + 1)]
for i in range(e):
u, v, w = map(int, input().split())
G[u].append([v, w])
for i in dijkstra(G, k)[1:]:
print(i if i != float('inf') else "INF")
from heapq import heappush, heappop
def dijkstra(G, start):
dp = [0 if v == start else float('inf') for v in range(len(G))]
heap = [(0, start)]
while heap:
w, n = heappop(heap)
for n_n, wei in G[n]:
n_w = wei + w
if n_w < dp[n_n]:
dp[n_n] = n_w
heappush(heap, [n_w, n_n])
return dp
n, m = map(int, input().split())
G = [[] for _ in range(n)]
for _ in range(m):
a, b, c = map(int, input().split())
G[a-1].append([b-1, c])
G[b-1].append([a-1, c])
x, y = map(int, input().split())
path1 = dijkstra(G, 0)[x-1] + dijkstra(G, x-1)[y-1] + dijkstra(G, y-1)[n-1]
path2 = dijkstra(G, 0)[y-1] + dijkstra(G, y-1)[x-1] + dijkstra(G, x-1)[n-1]
ans = min(path1, path2)
print(ans if ans < float('inf') else "-1")
from heapq import heappush, heappop
import sys
input = sys.stdin.readline
def dijkstra(G, start, shortests):
heap = [(0, start)]
dp = [0 if start == i else float('inf') for i in range(n + 1)]
while heap:
w, v = heappop(heap)
for adj, nw in G[v].items():
wei = nw + w
if dp[adj] > wei:
dp[adj] = wei
heappush(heap, (wei, adj))
shortests[adj][start] = v
return shortests
n, m = map(int, input().split())
G = [{} for i in range(n + 1)]
shortests = [[0] * n for i in range(n)]
for i in range(m):
u, v, w = map(int, input().split())
G[u - 1][v - 1] = w
G[v - 1][u - 1] = w
for i in range(n):
dijkstra(G, i, shortests)
for i in range(n):
for j in range(n):
if i == j:
print("-", end=" ")
else:
print(shortests[i][j] + 1, end=" ")
print()
from heapq import heappush, heappop
from collections import defaultdict
def dijkstra(G):
dp = defaultdict(lambda : float('inf'), {(0, 0) : 0})
heap = [(0, 0, 0)]
while heap:
w, r, c = heappop(heap)
for nr, nc in [(r + 1, c), (r, c + 1), (r - 1, c), (r, c - 1)]:
if 0 <= nr < len(G) and 0 <= nc < len(G):
nw = w + (0 if G[r][c] == '1' else 1)
if nw < dp[(nr, nc)]:
dp[(nr, nc)] = nw
heappush(heap, (nw, nr, nc))
return dp
N = int(input())
G = [input() for _ in range(N)]
print(dijkstra(G)[(len(G) - 1, len(G) - 1)])
Single source shortest path in
Can be used to detect negative-weight cycles
def bellman_ford(G, source):
dist, pre = dict(), dict()
for node in G:
dist[node], pre[node] = float('inf'), None
dist[source] = 0
for _ in range(len(G) - 1):
for node in G:
for nei in G[node]:
if dist[nei] > dist[node] + G[node][nei]:
dist[nei], pre[nei] = dist[node] + G[node][nei], node
for node in G:
for nei in G[node]:
assert dist[nei] <= dist[node] + G[node][nei], "Negative weight cycle."
return dist, pre
all pairs shortest pathSoftest path from every pair in O(V^3)
N = int(input())
G = [input().split() for _ in range(N)]
for i in range(N) :
for j in range(N) :
for k in range(N):
if G[j][i] == '1' and G[i][k] == '1':
G[j][k] = '1'
for i in range(N):
print(' '.join(G[i]))
BJ_1389 케빈 베이컨의 6단계 법칙 (Silver I)
V, E = map(int, input().split())
G = [[float('inf')] * V for _ in range(V)]
for i in range(V):
G[i][i] = 0
for _ in range(E):
u, v = map(int, input().split())
G[u - 1][v - 1] = 1
G[v - 1][u - 1] = 1
for i in range(V):
for j in range(V):
for k in range(V):
if G[j][i] + G[i][k] < G[j][k]:
G[j][k] = G[j][i] + G[i][k]
bacon_scores = [sum(li) for li in G]
print(bacon_scores.index(min(bacon_scores)) + 1)
V, E = int(input()), int(input())
G = [[float('inf')] * V for _ in range(V)]
for _ in range(E):
u, v, w = map(int, input().split())
G[u - 1][v - 1] = min(w, G[u - 1][v - 1])
for i in range(V):
for j in range(V):
for k in range(V):
if G[j][i] + G[i][k] < G[j][k]:
G[j][k] = G[j][i] + G[i][k]
for i in range(V):
for j, v in enumerate(G[i]):
if i == j or v == float('inf'):
print(0, end=' ')
else:
print(v, end=' ')
print()
Kosaraju's Algorithm Graph Algorithm
vector<int> v;
int find(int a) {
if (v[a] != a) return v[a] = find(v[a]);
return a;
}
void unions(int a, int b) {
v[find(b)] = find(a);
}
class UF:
def __init__(self, N):
self.parent = list(range(N))
self.size = [1] * N
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px != py:
size_x, size_y = self.size[px], self.size[py]
if size_x < size_y:
self.parent[px] = py
self.size[py] += size_x
else:
self.parent[py] = px
self.size[px] += size_y
n, m = map(int, input().split())
uf = UF(n)
for _ in range(m):
t, a, b = map(int, input().split())
a -= 1; b -= 1
if t == 0:
uf.union(a, b)
else:
print("YES" if uf.find(a) == uf.find(b) else "NO")
class UF:
def __init__(self, N):
self.parent = list(range(N))
self.size = [1] * N
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px != py:
size_x, size_y = self.size[px], self.size[py]
if size_x < size_y:
self.parent[px] = py
self.size[py] += size_x
else:
self.parent[py] = px
self.size[px] += size_y
V, E = map(int, input().split())
uf = UF(V)
weight_u_v = []
for _ in range(E):
u, v, w = map(int, input().split())
weight_u_v.append((w, u - 1, v - 1))
total = 0
weight_u_v.sort()
for weight, u, v in weight_u_v:
if uf.find(u) != uf.find(v):
total += weight
uf.union(u, v)
print(total)
class UF:
def __init__(self, N):
self.parent = list(range(N))
self.size = [1] * N
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px != py:
size_x, size_y = self.size[px], self.size[py]
if size_x < size_y:
self.parent[px] = py
self.size[py] += size_x
else:
self.parent[py] = px
self.size[px] += size_y
for _ in range(int(input())):
N = int(input())
name2idx, names = {}, [input() for _ in range(N)]
uf = UF(N * 2)
for name in names:
a, b = name.split()
if a not in name2idx:
name2idx[a] = len(name2idx)
if b not in name2idx:
name2idx[b] = len(name2idx)
a, b = name2idx[a], name2idx[b]
uf.union(a, b)
print(max(uf.size[uf.find(a)], uf.size[uf.find(b)]))
BJ_2150 Strongly Connected Component (Platinum V)
import sys
sys.setrecursionlimit(10000)
def dfs(G, start, visited, stk = None):
visited.add(start)
for adj in G[start]:
if adj not in visited:
dfs(G, adj, visited, stk)
if stk != None:
stk.append(start)
V, E = map(int, input().split())
G, G_inv = [[] for _ in range(V)], [[] for _ in range(V)]
for _ in range(E):
v1, v2 = map(int, input().split())
G[v1 - 1].append(v2 - 1)
G_inv[v2 - 1].append(v1 - 1)
visited, stk = set(), []
for v in range(V):
if v not in visited:
dfs(G, v, visited, stk)
visited, SCCs, scced = set(), [], set()
for v in reversed(stk):
if v not in visited:
dfs(G_inv, v, visited)
SCCs.append(visited - scced)
scced |= visited
print(len(SCCs))
for SCC in sorted(SCCs, key=lambda li: min(li)):
print(*sorted(SCC), -1)
LC_952 largest-component-size-by-common-factor (Hard)
import collections
import math
class UF:
def __init__(self, N):
self.parent = list(range(N))
self.size = [1] * N
def find(self, x):
if self.parent[x] != x:
self.parent[x] = self.find(self.parent[x])
return self.parent[x]
def union(self, x, y):
px, py = self.find(x), self.find(y)
if px != py:
size_x, size_y = self.size[px], self.size[py]
if size_x < size_y:
self.parent[px] = py
self.size[py] += size_x
else:
self.parent[py] = px
self.size[px] += size_y
class Solution:
def largestComponentSize(self, A: List[int]) -> int:
factor2i = collections.defaultdict(int)
uf = UF(len(A))
for i, num in enumerate(A):
for factor in range(2, int(math.sqrt(num) + 1)):
if num % factor == 0:
for fac in (factor, num // factor):
if fac in factor2i:
uf.union(i, factor2i[fac])
else:
factor2i[fac] = i
if num not in factor2i:
factor2i[num] = i
else:
uf.union(i, factor2i[num])
return max(uf.size)
import sys
input = sys.stdin.readline
def topologicalSort(G):
indegree = [0] * N
for dic in G:
for adj in dic.keys():
indegree[adj] += 1
order, id2cost = [], [0] * N
for i in range(N):
if indegree[i] == 0:
id2cost[i] = D[i]
order.append(i)
for v in order:
for adj, cost in G[v].items():
id2cost[adj] = max(id2cost[adj], id2cost[v] + cost)
indegree[adj] -= 1
if indegree[adj] == 0:
order.append(adj)
return id2cost
T = int(input())
for _ in range(T):
N, K = map(int, input().split())
D = list(map(int, input().split()))
G = [{} for _ in range(N)]
for _ in range(K):
X, Y = map(int, input().split())
G[X - 1][Y - 1] = D[Y - 1]
W = int(input()) - 1
print(topologicalSort(G)[W])
N, costs = int(input()), []
G, G_r = [[] for i in range(N)], [[] for i in range(N)]
wait = [0] * N
for u in range(N):
li = list(map(int, input().split()))
costs.append(li[0])
for v in li[1:-1]:
G[v - 1].append(u)
G_r[u].append(v - 1)
wait[u] += 1
bfs = [n for n in range(N) if wait[n] == 0]
for i in bfs:
for j in G[i]:
wait[j] -= 1
if wait[j] == 0:
bfs.append(j)
for i in bfs:
costs[i] += max([0] + [costs[j] for j in G_r[i]])
print(*costs, sep='\n')
N, M = map(int, input().split())
G = [[] for i in range(N + 1)]
wait = [-1] + [0] * (N)
for _ in range(M):
u, v = map(int, input().split())
G[u].append(v)
wait[v] += 1
bfs = [n for n in range(N + 1) if wait[n] == 0]
print(*bfs, end=' ')
for i in bfs:
for j in G[i]:
wait[j] -= 1
if wait[j] == 0:
print(j, end=' ')
bfs.append(j)
def canFinish(n, prerequisites):
G = [[] for i in range(n)]
degree = [0] * n
for i, j in prerequisites:
G[i].append(j) # Take i before j
degree[j] += 1
bfs = [i for i in range(n) if degree[i] == 0]
for i in bfs:
for j in G[i]:
degree[j] -= 1
if degree[j] == 0:
bfs.append(j)
return len(bfs) == n
case v = root
vertex will be the point of articulation iff this vertex has more than one child.
case v ≠ root.
During DFS, (v, to) is articulation iff none of the vertices to or its descendents in the DFS traversal tree has a back-edge to any of the ancestors of v, then v is an articulation point.
visited time ≤ low time of adjacent vertex
def dfs(G, start, visited):
if start not in visited:
visited.add(start)
for adj in G[start]:
if adj not in cow2home or dfs(G, cow2home[adj], visited):
cow2home[adj] = start
return 1
return 0
n_home, n_cow = map(int, input().split())
G = [[] for _ in range(n_home)]
cow2home = {}
for home in range(n_home):
for cow in list(map(int, input().split()))[1:]:
G[home].append(cow - 1)
for i in range(n_home):
dfs(G, i, set())
print(len(cow2home))
def dfs(G, start, visited, ppl2work):
if start not in visited:
visited.add(start)
for adj in G[start]:
if adj not in ppl2work or dfs(G, ppl2work[adj], visited, ppl2work):
ppl2work[adj] = start
return 1
return 0
n_people, n_work = map(int, input().split())
G = [[] for _ in range(n_people)]
ppl2work = {}
for home in range(n_people):
for cow in list(map(int, input().split()))[1:]:
G[home].append(cow - 1)
for i in range(n_people):
dfs(G, i, set(), ppl2work)
print(len(ppl2work))
vector<vector<int>> criticalConnections(int n, vector<vector<int>>& connections) {
vector<bool> vi(n, false);
vector<int> disc(n, 0), low(n, 0), parent(n, -1);
vector<vector<int>> g(n, vector<int>()), res;
for (auto& p : connections) {
g[p.front()].push_back(p.back());
g[p.back()].push_back(p.front());
}
for (int i = 0; i < n; ++i) {
if (vi[i]) continue;
h(i, vi, disc, low, parent, g, res);
}
return res;
}
void h(int u, vector<bool>& vi, vector<int>& disc, vector<int>& low, vector<int>& parent, vector<vector<int>>& g, vector<vector<int>>& res) {
static int time = 0;
vi[u] = true;
disc[u] = low[u] = ++time;
for (int v : g[u]) {
if (!vi[v]) {
parent[v] = u;
h(v, vi, disc, low, parent, g, res);
low[u] = min(low[u], low[v]);
if (low[v] > disc[u]) {
res.push_back({u, v});
}
} else if (v != parent[u]) {
low[u] = min(low[u], disc[v]);
}
}
}
from threading import Lock
class Foo:
def __init__(self):
self.locks = (Lock(),Lock())
self.locks[0].acquire()
self.locks[1].acquire()
def first(self, printFirst):
printFirst()
self.locks[0].release()
def second(self, printSecond):
with self.locks[0]:
printSecond()
self.locks[1].release()
def third(self, printThird):
with self.locks[1]:
printThird()
LC_1195 fizz-buzz-multithreaded
from threading import Semaphore
class FizzBuzz(object):
def __init__(self, n):
self.n = n
self.sem0 = Semaphore(1)
self.sem3 = Semaphore(0)
self.sem5 = Semaphore(0)
self.sem15 = Semaphore(0)
def fizz(self, printFizz):
for i in range(3, self.n + 1, 3):
if i % 15:
self.sem3.acquire()
printFizz()
self._release(i+1)
def buzz(self, printBuzz):
for i in range(5, self.n + 1, 5):
if i % 15:
self.sem5.acquire()
printBuzz()
self._release(i+1)
def fizzbuzz(self, printFizzBuzz):
for i in range(15, self.n + 1, 15):
self.sem15.acquire()
printFizzBuzz()
self._release(i+1)
def number(self, printNumber):
for i in range(1, self.n + 1):
if i % 3 and i % 5:
self.sem0.acquire()
printNumber(i)
self._release(i+1)
def _release(self, i):
if i % 3 and i % 5:
self.sem0.release()
elif i % 5:
self.sem3.release()
elif i % 3:
self.sem5.release()
else:
self.sem15.release()
LC_1115 print-foobar-alternately
from threading import Semaphore
class FooBar:
def __init__(self, n):
self.n = n
self.semF = Semaphore(1)
self.semB = Semaphore(0)
def foo(self, printFoo: 'Callable[[], None]') -> None:
for i in range(self.n):
self.semF.acquire()
printFoo()
self.semB.release()
def bar(self, printBar: 'Callable[[], None]') -> None:
for i in range(self.n):
self.semB.acquire()
printBar()
self.semF.release()
from threading import Semaphore
class ZeroEvenOdd:
def __init__(self, n):
self.n = n
self.semZ = Semaphore(1)
self.semO = Semaphore(0)
self.semE = Semaphore(0)
def zero(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(self.n):
self.semZ.acquire()
printNumber(0)
(self.semE if i % 2 else self.semO).release()
def even(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(2, self.n + 1, 2):
self.semE.acquire()
printNumber(i)
self.semZ.release()
def odd(self, printNumber: 'Callable[[int], None]') -> None:
for i in range(1, self.n + 1, 2):
self.semO.acquire()
printNumber(i)
self.semZ.release()
from threading import Barrier, Semaphore
class H2O:
def __init__(self):
self.b = Barrier(3)
self.h = Semaphore(2)
self.o = Semaphore(1)
def hydrogen(self, releaseHydrogen: 'Callable[[], None]') -> None:
self.h.acquire()
self.b.wait()
releaseHydrogen()
self.h.release()
def oxygen(self, releaseOxygen: 'Callable[[], None]') -> None:
self.o.acquire()
self.b.wait()
releaseOxygen()
self.o.release()
class Twitter(object):
def __init__(self):
self.timer = itertools.count(step=-1)
self.tweets = collections.defaultdict(collections.deque)
self.followees = collections.defaultdict(set)
def postTweet(self, userId, tweetId):
self.tweets[userId].appendleft((next(self.timer), tweetId))
def getNewsFeed(self, userId):
tweets = heapq.merge(*(self.tweets[u] for u in self.followees[userId] | {userId}))
return [t for _, t in heapq.nsmallest(10, tweets)]
def follow(self, followerId, followeeId):
self.followees[followerId].add(followeeId)
def unfollow(self, followerId, followeeId):
self.followees[followerId].discard(followeeId)
read a b
echo $(($a+$b))
read A B
echo $(($A+$B))
echo $(($A-$B))
echo $(($A*$B))
echo $(($A/$B))
echo $(($A%$B))
read a b
echo $(($a==$b))
read a
if [ $a -ge 90 ]; then
echo "A"
elif [ $a -ge 80 ]; then
echo "B"
elif [ $a -ge 70 ]; then
echo "C"
elif [ $a -ge 60 ]; then
echo "D"
else
echo "F"
fi
read n
for i in {1..9}
do
echo "$n * $i = $(($n*$i))"
done
read N
for((i=1;i<=N;i++))
do
for((j=1;j<=$i;j++))
do
printf "*"
done
echo
done
awk 'NR == 10' file.txt
BJ_11719 그대로 출력하기 2 (Bronze I)
#include <iostream>
int main() {
char c;
while((c = std::cin.get()) != -1) {
std::cout << c;
}
}
#include <iostream>
#include <cstdio>
using namespace std;
int main() {
int a, b;
while (scanf("%d%d", &a, &b) != EOF)
cout << a + b << endl;
}
// Inversion Count : sum of (mid - i) during merge step
// Stable
// Linked List
void mergeSort(int arr[], int l, int r) {
if (l < r) {
int m = l+(r-l)/2;
mergeSort(arr, l, m);
mergeSort(arr, m+1, r);
merge(arr, l, m, r);
}
}
void merge(int arr[], int l, int m, int r) {
int n1 = m - l + 1, n2 = r - m;
int L[n1], R[n2];
for (i = 0; i < n1; i++)
L[i] = arr[l + i];
for (j = 0; j < n2; j++)
R[j] = arr[m + 1+ j];
int i = 0, j = 0, k = l;
while (i < n1 && j < n2) {
if (L[i] <= R[j])
arr[k++] = L[i++];
else
arr[k++] = R[j++];
}
while (i < n1)
arr[k++] = L[i++];
while (j < n2)
arr[k++] = R[j++];
}
int partition (int arr[], int low, int high) {
int pivot = arr[high]; // pivot
int i = (low - 1); // Index of smaller element
for (int j = low; j < high; j++) {
if (arr[j] <= pivot) {
i++;
swap(&arr[i], &arr[j]);
}
}
swap(&arr[i + 1], &arr[high]);
return (i + 1);
}
void quickSort(int arr[], int low, int high) {
if (low < high) {
int pi = partition(arr, low, high);
quickSort(arr, low, pi - 1);
quickSort(arr, pi + 1, high);
}
}
# Search in rotated array
def search(li, targ):
lo, hi = 0, len(li) - 1
while lo < hi:
mi = (lo + hi) // 2
if (li[0] > targ) ^ (li[0] > li[mi]) ^ (targ > li[mi]):
lo = mi + 1
else:
hi = mi
return lo if targ in li[lo:lo+1] else -1
#include<iostream>
using namespace std;
int main() {
cin.tie(NULL);
ios::sync_with_stdio(false);
int T;
cin >> T;
while (T--) {
int A, B;
cin >> A >> B;
cout << A + B << '\n';
}
}
# Zellar’s formula
void randomize (int arr[], int n) {
srand (time(NULL));
for (int i = n - 1; i > 0; i--) {
int j = rand() % (i + 1);
swap(&arr[i], &arr[j]);
}
}
#include<iostream>
#include<string>
using namespace std;
int ans[10010];
int main() {
string a, b;
cin >> a >> b;
int x = a.length() - 1;
int y = b.length() - 1;
int i = 0;
for (i = 0; x >= 0 || y >= 0; i++) {
if (x >= 0) ans[i] += a[x] - '0';
if (y >= 0)ans[i] += b[y] - '0';
if (ans[i] > 9) {
ans[i + 1]++;
ans[i]-=10;
}
x--;
y--;
}
if (ans[i])cout << ans[i];
while (i--) {
cout << ans[i];
}
}
//
long powmod(long base, long exp, long modulus) {
base %= modulus;
long result = 1;
while (exp > 0) {
if (exp & 1) result = (result * base) % modulus;
base = (base * base) % modulus;
exp >>= 1;
}
return result;
}
//
int factmod (int n, int p) {
long long res = 1;
while (n > 1) {
res = (res * powmod (p-1, n/p, p)) % p;
for (int i=2; i<=n%p; ++i)
res=(res*i) %p;
n /= p;
}
return int (res % p);
}
// range GCD / minimum query
void buildSparseTable(int arr[], int N) {
// initialize M for the intervals with length 1
for (int i = 0; i < N; i++)
lookup[i][0] = arr[i];
// Compute values from smaller to bigger intervals
for (int j = 1; (1 << j) - 1) < N; i ++) {
for (int i = 0; (i + (1 << j) - 1) < N; i++) {
lookup[i][j] = min(lookup[i][j - 1], lookup[i + (1 << (j - 1))][j - 1]);
}
}
}
int query (int L, int R) {
int j = (int) log2(R - L + 1);
return min(lookup[L][j], lookup[R - (1 << j) + 1][j];
}
//MAXN = maximum points in the graph
vector<int> g[MAXN];
bool used[MAXN];
int timer, tin[MAXN], fup[MAXN];
void dfs (int v, int p = -1) {
used[v] = true;
tin[v] = fup[v] = timer++;
int children = 0;
for (size_t i=0; i<g[v].size(); ++i) {
int to = g[v][i];
if (to == p) continue;
if (used[to])
fup[v] = min (fup[v], tin[to]);
else {
dfs (to, v);
fup[v] = min (fup[v], fup[to]);
if (fup[to] >= tin[v] && p != -1)
//v is articulation point
++children;
}
}
if (p == -1 && children > 1)
//v is articulation point
}
int main() {
int n;
// read n and g
timer = 0;
for (int i=0; i<n; ++i)
used[i] = false;
dfs (0);
}
https://www.youtube.com/watch?v=tZooW6PritE&list=PLuHgQVnccGMDZP7FJ_ZsUrdCGH68ppvPb
https://www.youtube.com/watch?v=kN6mlybyTdA&list=PLuHgQVnccGMDMxfZEpLbzHPZUEwObEaZq&index=1
{% endblock body %}